<html><head>
      <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
   <title>4.&nbsp;The IoC container</title><link rel="stylesheet" href="css/stylesheet.css" type="text/css"><meta name="generator" content="DocBook XSL Stylesheets V1.74.0"><link rel="home" href="index.html" title="Reference Documentation"><link rel="up" href="spring-core.html" title="Part&nbsp;III.&nbsp;Core Technologies"><link rel="prev" href="spring-core.html" title="Part&nbsp;III.&nbsp;Core Technologies"><link rel="next" href="resources.html" title="5.&nbsp;Resources"><!--Begin Google Analytics code--><script type="text/javascript">
			var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
			document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));
		</script><script type="text/javascript">
			var pageTracker = _gat._getTracker("UA-2728886-3");
			pageTracker._setDomainName("none");
			pageTracker._setAllowLinker(true);
			pageTracker._trackPageview();
		</script><!--End Google Analytics code--></head><body bgcolor="white" text="black" link="#0000FF" vlink="#840084" alink="#0000FF"><div class="navheader"><table width="100%" summary="Navigation header"><tr><th colspan="3" align="center">4.&nbsp;The IoC container</th></tr><tr><td width="20%" align="left"><a accesskey="p" href="spring-core.html">Prev</a>&nbsp;</td><th width="60%" align="center">Part&nbsp;III.&nbsp;Core Technologies</th><td width="20%" align="right">&nbsp;<a accesskey="n" href="resources.html">Next</a></td></tr></table><hr></div><div class="chapter" lang="en"><div class="titlepage"><div><div><h2 class="title"><a name="beans"></a>4.&nbsp;The IoC container</h2></div></div></div><div class="section" lang="en"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="beans-introduction"></a>4.1&nbsp;Introduction to the Spring IoC container and beans</h2></div></div></div><p>This chapter covers the Spring Framework implementation of the
      Inversion of Control (IoC) <sup>[<a name="d0e1637" href="#ftn.d0e1637" class="footnote">1</a>]</sup>principle. IoC is also known as <span class="emphasis"><em>dependency
      injection</em></span> (DI). It is a process whereby objects define their
      dependencies, that is, the other objects they work with, only through
      constructor arguments, arguments to a factory method, or properties that
      are set on the object instance after it is constructed or returned from a
      factory method. The container then <span class="emphasis"><em>injects</em></span> those
      dependencies when it creates the bean. This process is fundamentally the
      inverse, hence the name <span class="emphasis"><em>Inversion of Control</em></span> (IoC),
      of the bean itself controlling the instantiation or location of its
      dependencies by using direct construction of classes, or a mechanism such
      as the <span class="emphasis"><em>Service Locator</em></span> pattern.</p><p>The <code class="literal">org.springframework.beans</code> and
      <code class="literal">org.springframework.context</code> packages are the basis for
      Spring Framework's IoC container. The <code class="interfacename"><a class="ulink" href="http://static.springframework.org/spring/docs/3.0.x/javadoc-api/org/springframework/beans/factory/BeanFactory.html" target="_top">BeanFactory</a></code> interface provides an advanced
      configuration mechanism capable of managing any type of object.
      <code class="literal"><a class="ulink" href="http://static.springframework.org/spring/docs/3.0.x/javadoc-api/org/springframework/context/ApplicationContext.html" target="_top">ApplicationContext</a></code> is a sub-interface of
      <code class="interfacename">BeanFactory.</code> It adds easier integration
      with Spring's AOP features; message resource handling (for use in
      internationalization), event publication; and application-layer specific
      contexts such as the <code class="interfacename">WebApplicationContext</code>
      for use in web applications.</p><p>In short, the <code class="interfacename">BeanFactory</code> provides the
      configuration framework and basic functionality, and the
      <code class="interfacename">ApplicationContext</code> adds more
      enterprise-specific functionality. The
      <code class="interfacename">ApplicationContext</code> is a complete superset
      of the <code class="interfacename">BeanFactory</code>, and is used exclusively
      in this chapter in descriptions of Spring's IoC container.
      For
      more information on using the <code class="classname">BeanFactory</code> instead
      of the <code class="classname">ApplicationContext,</code> refer to <a class="xref" href="beans.html#beans-beanfactory" title="4.15&nbsp;The BeanFactory">Section&nbsp;4.15, &#8220;The BeanFactory&#8221;</a>.</p><p>In Spring, the objects that form the backbone of your application and
      that are managed by the Spring IoC <em class="firstterm">container</em> are
      called <em class="firstterm">beans</em>. A bean is an object that is
      instantiated, assembled, and otherwise managed by a Spring IoC container.
      Otherwise, a bean is simply one of many objects in your application.
      Beans, and the <em class="firstterm">dependencies</em> among them, are
      reflected in the <em class="firstterm">configuration metadata</em> used by a
      container.</p></div><div class="section" lang="en"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="beans-basics"></a>4.2&nbsp;Container overview</h2></div></div></div><p>The interface
      <code class="classname">org.springframework.context.ApplicationContext</code>
      represents the Spring IoC container and is responsible for instantiating,
      configuring, and assembling the aforementioned beans. The container gets
      its instructions on what objects to instantiate, configure, and assemble
      by reading configuration metadata. The configuration metadata is
      represented in XML, Java annotations, or Java code. It allows you to
      express the objects that compose your application and the rich
      interdependencies between such objects.</p><p>Several implementations of the
      <code class="classname">ApplicationContext</code> interface are supplied
      out-of-the-box with Spring. In standalone applications it is common to
      create an instance of <a class="ulink" href="http://static.springsource.org/spring/docs/3.0.x/javadoc-api/org/springframework/context/support/ClassPathXmlApplicationContext.html" target="_top"><code class="classname">ClassPathXmlApplicationContext</code></a> or <a class="ulink" href="http://static.springsource.org/spring/docs/3.0.x/javadoc-api/org/springframework/context/support/FileSystemXmlApplicationContext.html" target="_top"><code class="classname">FileSystemXmlApplicationContext</code></a>.
       While XML has been the traditional format
      for defining configuration metadata you can instruct the container to use
      Java annotations or code as the metadata format by providng a small amount
      of XML configuration to declaratively enable support for these additional
      metadata formats.</p><p>In most application scenarios, explicit user code is not required to
      instantiate one or more instances of a Spring IoC container. For example,
      in a web application scenario, a simple eight (or so) lines of boilerplate
      J2EE web descriptor XML in the <code class="literal">web.xml</code> file of the
      application will typically suffice (see <a class="xref" href="beans.html#context-create" title="4.14.4&nbsp;Convenient ApplicationContext instantiation for web applications">Section&nbsp;4.14.4, &#8220;Convenient ApplicationContext
      instantiation for web applications&#8221;</a>).
      If you are using the <a class="ulink" href="http://www.springsource.com/produts/sts" target="_top">SpringSource Tool Suite</a> Eclipse-powered development environment
      or <a class="ulink" href="http://www.springsource.org/roo" target="_top">Spring Roo</a> this
      boilerplate configuration can be easily created with few mouse clicks or
      keystrokes.</p><p>The following diagram is a high-level view of how Spring works. Your
      application classes are combined with configuration metadata so that after
      the <code class="classname">ApplicationContext</code> is created and initialized,
      you have a fully configured and executable system or application.</p><div class="mediaobject" align="center"><img src="images/container-magic.png" align="middle"><div class="caption"><p>The Spring IoC container</p></div></div><div class="section" lang="en"><div class="titlepage"><div><div><h3 class="title"><a name="beans-factory-metadata"></a>4.2.1&nbsp;Configuration metadata</h3></div></div></div><p>As the preceding diagram shows, the Spring IoC container consumes a
        form of <span class="emphasis"><em>configuration metadata</em></span>; this configuration
        metadata represents how you as an application developer tell the Spring
        container to instantiate, configure, and assemble the objects in your
        application.</p><p>Configuration metadata is traditionally supplied in a simple and
        intuitive XML format, which is what most of this chapter uses to convey
        key concepts and features of the Spring IoC container.</p><div class="note" style="margin-left: 0.5in; margin-right: 0.5in;"><table border="0" summary="Note"><tr><td rowspan="2" align="center" valign="top" width="25"><img alt="[Note]" src="images/note.gif"></td><th align="left">Note</th></tr><tr><td align="left" valign="top"><p>XML-based metadata is <span class="emphasis"><em>not</em></span> the only allowed
          form of configuration metadata. The Spring IoC container itself is
          <span class="emphasis"><em>totally</em></span> decoupled from the format in which this
          configuration metadata is actually written.</p></td></tr></table></div><p>For information about using other forms of metadata with the Spring
        container, see:</p><div class="itemizedlist"><ul type="disc"><li><p><a class="link" href="beans.html#beans-annotation-config" title="4.9&nbsp;Annotation-based container configuration">Annotation-based
            configuration</a>: Spring 2.5 introduced support for
            annotation-based configuration metadata.</p></li><li><p><a class="link" href="beans.html#beans-java" title="4.12&nbsp;Java-based container configuration">Java-based configuration</a>:
            Starting with Spring 3.0, many features provided by the <a class="ulink" href="http://www.springsource.org/javaconfig" target="_top">Spring JavaConfig
            project</a> became part of the core Spring Framework. Thus you
            can define beans external to your application classes by using Java
            rather than XML files. To use these new features, see the
            <code class="interfacename">@Configuration</code>, <code class="interfacename">@Bean,
            @Import</code> and
            <code class="interfacename">@DependsOn</code> annotations.</p></li></ul></div><p>Spring configuration consists of at least one and typically more
        than one bean definition that the container must manage. XML-based
        configuration metadata shows these beans configured as
        <code class="literal">&lt;bean/&gt;</code> elements inside a top-level
        <code class="literal">&lt;beans/&gt;</code> element.</p><p>These bean definitions correspond to the actual objects that make up
        your application. Typically you define service layer objects, data
        access objects (DAOs), presentation objects such as Struts
        <code class="interfacename">Action</code> instances, infrastructure objects
        such as Hibernate <code class="interfacename">SessionFactories</code>, JMS
        <code class="interfacename">Queues</code>, and so forth. Typically one does
        not configure fine-grained domain objects in the container, because it
        is usually the responsibility of DAOs and business logic to create and
        load domain objects. However, you can use Spring's integration with
        AspectJ to configure objects that have been created outside the control
        of an IoC container. See <a class="link" href="aop.html#aop-atconfigurable" title="8.8.1&nbsp;Using AspectJ to dependency inject domain objects with Spring">Using
        AspectJ to dependency-inject domain objects with Spring</a>.</p><p>The following example shows the basic structure of XML-based
        configuration metadata:</p><pre class="programlisting">&lt;<span class="hl-tag">?xml version="1.0" encoding="UTF-8"?</span>&gt;
&lt;<span class="hl-tag">beans</span> <span class="hl-attribute">xmlns</span>=<span class="hl-value">"http://www.springframework.org/schema/beans"</span>
       <span class="hl-attribute">xmlns:xsi</span>=<span class="hl-value">"http://www.w3.org/2001/XMLSchema-instance"</span>
       <span class="hl-attribute">xsi:schemaLocation</span>=<span class="hl-value">"http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"</span>&gt;

  &lt;<span class="hl-tag">bean</span> <span class="hl-attribute">id</span>=<span class="hl-value">"..."</span> <span class="hl-attribute">class</span>=<span class="hl-value">"..."</span>&gt;
    &lt;<span class="hl-comment">!-- collaborators and configuration for this bean go here --</span>&gt;
  &lt;<span class="hl-tag">/bean</span>&gt;

  &lt;<span class="hl-tag">bean</span> <span class="hl-attribute">id</span>=<span class="hl-value">"..."</span> <span class="hl-attribute">class</span>=<span class="hl-value">"..."</span>&gt;
    &lt;<span class="hl-comment">!-- collaborators and configuration for this bean go here --</span>&gt;
  &lt;<span class="hl-tag">/bean</span>&gt;

  &lt;<span class="hl-comment">!-- more bean definitions go here --</span>&gt;

&lt;<span class="hl-tag">/beans</span>&gt;</pre><p>The <code class="literal">id</code> attribute is a string that you use to
        identify the individual bean definition. The <code class="literal">class</code>
        attribute defines the type of the bean and uses the fully qualified
        classname. The value of the id attribute refers to collaborating
        objects. The XML for referring to collaborating objects is not shown in
        this example; see <a class="link" href="beans.html#beans-dependencies" title="4.4&nbsp;Dependencies">Dependencies</a>
        for more information.</p></div><div class="section" lang="en"><div class="titlepage"><div><div><h3 class="title"><a name="beans-factory-instantiation"></a>4.2.2&nbsp;Instantiating a container</h3></div></div></div><p>Instantiating a Spring IoC container is straightforward. The
        location path or paths supplied to an
        <code class="interfacename">ApplicationContext</code> constructor are
        actually resource strings that allow the container to load configuration
        metadata from a variety of external resources such as the local file
        system, from the Java <code class="literal">CLASSPATH</code>, and so on.</p><pre class="programlisting">ApplicationContext context =
    <span class="hl-keyword">new</span> ClassPathXmlApplicationContext(<span class="hl-keyword">new</span> String[] {<span class="hl-string">"services.xml"</span>, <span class="hl-string">"daos.xml"</span>});</pre><div class="note" style="margin-left: 0.5in; margin-right: 0.5in;"><table border="0" summary="Note"><tr><td rowspan="2" align="center" valign="top" width="25"><img alt="[Note]" src="images/note.gif"></td><th align="left">Note</th></tr><tr><td align="left" valign="top"><p>After you learn about Spring's IoC container, you may want to know
          more about Spring's <code class="interfacename">Resource</code>
          abstraction, as described in <a class="xref" href="resources.html" title="5.&nbsp;Resources">Chapter&nbsp;5, <i>Resources</i></a>, which
          provides a convenient mechanism for reading an InputSream from
          locations defined in a URI syntax. In particular,
          <code class="classname">Resource</code> paths are used to construct
          applications contexts as described in <a class="xref" href="resources.html#resources-app-ctx" title="5.7&nbsp;Application contexts and Resource paths">Section&nbsp;5.7, &#8220;Application contexts and Resource paths&#8221;</a>.</p></td></tr></table></div><p>The following example shows the service layer objects
        <code class="literal">(services.xml)</code> configuration file:</p><pre class="programlisting">&lt;<span class="hl-tag">?xml version="1.0" encoding="UTF-8"?</span>&gt;
&lt;<span class="hl-tag">beans</span> <span class="hl-attribute">xmlns</span>=<span class="hl-value">"http://www.springframework.org/schema/beans"</span>
       <span class="hl-attribute">xmlns:xsi</span>=<span class="hl-value">"http://www.w3.org/2001/XMLSchema-instance"</span>
       <span class="hl-attribute">xsi:schemaLocation</span>=<span class="hl-value">"http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"</span>&gt;

  &lt;<span class="hl-comment">!-- services --</span>&gt;

  &lt;<span class="hl-tag">bean</span> <span class="hl-attribute">id</span>=<span class="hl-value">"petStore"</span>
        <span class="hl-attribute">class</span>=<span class="hl-value">"org.springframework.samples.jpetstore.services.PetStoreServiceImpl"</span>&gt;
    &lt;<span class="hl-tag">property</span> <span class="hl-attribute">name</span>=<span class="hl-value">"accountDao"</span> <span class="hl-attribute">ref</span>=<span class="hl-value">"accountDao"</span>/&gt;
    &lt;<span class="hl-tag">property</span> <span class="hl-attribute">name</span>=<span class="hl-value">"itemDao"</span> <span class="hl-attribute">ref</span>=<span class="hl-value">"itemDao"</span>/&gt;
    &lt;<span class="hl-comment">!-- additional collaborators and configuration for this bean go here --</span>&gt;
  &lt;<span class="hl-tag">/bean</span>&gt;

  &lt;<span class="hl-comment">!-- more bean definitions for services go here --</span>&gt;

&lt;<span class="hl-tag">/beans</span>&gt;
</pre><p>The following example shows the data access objects
        <code class="literal">daos.xml</code> file:</p><pre class="programlisting">&lt;<span class="hl-tag">?xml version="1.0" encoding="UTF-8"?</span>&gt;
&lt;<span class="hl-tag">beans</span> <span class="hl-attribute">xmlns</span>=<span class="hl-value">"http://www.springframework.org/schema/beans"</span>
       <span class="hl-attribute">xmlns:xsi</span>=<span class="hl-value">"http://www.w3.org/2001/XMLSchema-instance"</span>
       <span class="hl-attribute">xsi:schemaLocation</span>=<span class="hl-value">"http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"</span>&gt;

  &lt;<span class="hl-tag">bean</span> <span class="hl-attribute">id</span>=<span class="hl-value">"accountDao"</span>
      <span class="hl-attribute">class</span>=<span class="hl-value">"org.springframework.samples.jpetstore.dao.ibatis.SqlMapAccountDao"</span>&gt;
    &lt;<span class="hl-comment">!-- additional collaborators and configuration for this bean go here --</span>&gt;
  &lt;<span class="hl-tag">/bean</span>&gt;

  &lt;<span class="hl-tag">bean</span> <span class="hl-attribute">id</span>=<span class="hl-value">"itemDao"</span> <span class="hl-attribute">class</span>=<span class="hl-value">"org.springframework.samples.jpetstore.dao.ibatis.SqlMapItemDao"</span>&gt;
    &lt;<span class="hl-comment">!-- additional collaborators and configuration for this bean go here --</span>&gt;
  &lt;<span class="hl-tag">/bean</span>&gt;

  &lt;<span class="hl-comment">!-- more bean definitions for data access objects go here --</span>&gt;

&lt;<span class="hl-tag">/beans</span>&gt;</pre><p>In the preceding example, the service layer consists of the class
        <code class="classname">PetStoreServiceImpl</code>, and two data access objects
        of the type <code class="classname">SqlMapAccountDao</code> and SqlMapItemDao
        are based on the <a class="ulink" href="http://ibatis.apache.org/" target="_top">iBatis</a>
        Object/Relational mapping framework. The <code class="literal">property
        name</code> element refers to the name of the JavaBean property, and
        the <code class="literal">ref</code> element refers to the name of another bean
        definition. This linkage between id and ref elements expresses the
        dependency between collaborating objects. For details of configuring an
        object's dependencies, see <a class="link" href="beans.html#beans-dependencies" title="4.4&nbsp;Dependencies">Dependencies</a>.</p><div class="section" lang="en"><div class="titlepage"><div><div><h4 class="title"><a name="beans-factory-xml-import"></a>4.2.2.1&nbsp;Composing XML-based configuration metadata</h4></div></div></div><p>It can be useful to have bean definitions span multiple XML files.
          Often each individual XML configuration file represents a logical
          layer or module in your architecture.</p><p>You can use the application context constructor to load bean
          definitions from all these XML fragments. This constructor takes
          multiple <code class="interfacename">Resource</code> locations, as was
          shown in the previous section. Alternatively, use one or more
          occurrences of the <code class="literal">&lt;import/&gt;</code> element to load
          bean definitions from another file or files. For example:</p><pre class="programlisting">&lt;<span class="hl-tag">beans</span>&gt;

    &lt;<span class="hl-tag">import</span> <span class="hl-attribute">resource</span>=<span class="hl-value">"services.xml"</span>/&gt;
    &lt;<span class="hl-tag">import</span> <span class="hl-attribute">resource</span>=<span class="hl-value">"resources/messageSource.xml"</span>/&gt;
    &lt;<span class="hl-tag">import</span> <span class="hl-attribute">resource</span>=<span class="hl-value">"/resources/themeSource.xml"</span>/&gt;

    &lt;<span class="hl-tag">bean</span> <span class="hl-attribute">id</span>=<span class="hl-value">"bean1"</span> <span class="hl-attribute">class</span>=<span class="hl-value">"..."</span>/&gt;
    &lt;<span class="hl-tag">bean</span> <span class="hl-attribute">id</span>=<span class="hl-value">"bean2"</span> <span class="hl-attribute">class</span>=<span class="hl-value">"..."</span>/&gt;

&lt;<span class="hl-tag">/beans</span>&gt;</pre><p>In the preceding example, external bean definitions are loaded
          from three files, <code class="literal">services.xml</code>,
          <code class="literal">messageSource.xml</code>, and
          <code class="literal">themeSource.xml</code>. All location paths are relative to
          the definition file doing the importing, so
          <code class="literal">services.xml</code> must be in the same directory or
          classpath location as the file doing the importing, while
          <code class="literal">messageSource.xml</code> and
          <code class="literal">themeSource.xml</code> must be in a
          <code class="literal">resources</code> location below the location of the
          importing file. As you can see, a leading slash is ignored, but given
          that these paths are relative, it is better form not to use the slash
          at all. The contents of the files being imported, including the top
          level <code class="literal">&lt;beans/&gt;</code> element, must be valid XML
          bean definitions according to the Spring Schema or DTD.</p><div class="note" style="margin-left: 0.5in; margin-right: 0.5in;"><table border="0" summary="Note"><tr><td rowspan="2" align="center" valign="top" width="25"><img alt="[Note]" src="images/note.gif"></td><th align="left">Note</th></tr><tr><td align="left" valign="top"><p>It is possible, but not recommended, to reference files in
            parent directories using a relative "../" path. Doing so creates a
            dependency on a file that is outside the current application. In
            particular, this reference is not recommended for "classpath:" URLs
            (for example, "classpath:../services.xml"), where the runtime
            resolution process chooses the "nearest" classpath root and then
            looks into its parent directory. Classpath configuration changes may
            lead to the choice of a different, incorrect directory.</p><p>You can always use fully qualified resource locations instead of
            relative paths: for example, "file:C:/config/services.xml" or
            "classpath:/config/services.xml". However, be aware that you are
            coupling your application's configuration to specific absolute
            locations. It is generally preferable to keep an indirection for
            such absolute locations, for example, through "${...}" placeholders
            that are resolved against JVM system properties at runtime.</p></td></tr></table></div></div></div><div class="section" lang="en"><div class="titlepage"><div><div><h3 class="title"><a name="beans-factory-client"></a>4.2.3&nbsp;Using the container</h3></div></div></div><p>The <code class="interfacename">ApplicationContext</code> is the
        interface for an advanced factory capable of maintaining a registry of
        different beans and their dependencies. Using the method <code class="methodname">T
        getBean(Stringname, Class&lt;T&gt; requiredType)</code> you can
        retrieve instances of your beans.</p><p>The <code class="interfacename">ApplicationContext</code> enables you to
        read bean definitions and access them as follows:</p><pre class="programlisting"><span class="hl-comment">// create and configure beans</span>
ApplicationContext context =
    <span class="hl-keyword">new</span> ClassPathXmlApplicationContext(<span class="hl-keyword">new</span> String[] {<span class="hl-string">"services.xml"</span>, <span class="hl-string">"daos.xml"</span>});

<span class="hl-comment">// retrieve configured instance</span>
PetStoreServiceImpl service = context.getBean(<span class="hl-string">"petStore"</span>, PetStoreServiceImpl.<span class="hl-keyword">class</span>);

<span class="hl-comment">// use configured instance</span>
List userList service.getUsernameList();
</pre><p>You use <code class="methodname">getBean()</code> to retrieve instances of
        your beans. The <code class="interfacename">ApplicationContext</code>
        interface has a few other methods for retrieving beans, but ideally your
        application code should never use them. Indeed, your application code
        should have no calls to the <code class="methodname">getBean()</code> method at
        all, and thus no dependency on Spring APIs at all. For example, Spring's
        integration with web frameworks provides for dependency injection for
        various web framework classes such as controllers and JSF-managed
        beans.</p></div></div><div class="section" lang="en"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="beans-definition"></a>4.3&nbsp;Bean overview</h2></div></div></div><p>A Spring IoC container manages one or more <span class="emphasis"><em>beans</em></span>.
      These beans are created with the configuration metadata that you supply to
      the container, for example, in the form of XML
      <code class="literal">&lt;bean/&gt;</code> definitions.</p><p>Within the container itself, these bean definitions are represented as
      <code class="interfacename">BeanDefinition</code> objects, which contain
      (among other information) the following metadata:</p><div class="itemizedlist"><ul type="disc"><li><p><span class="emphasis"><em>A package-qualified class name:</em></span> typically the
          actual implementation class of the bean being defined.</p></li><li><p>Bean behavioral configuration elements, which state how the bean
          should behave in the container (scope, lifecycle callbacks, and so
          forth).</p></li><li><p>References to other beans that are needed for the bean to do its
          work; these references are also called
          <span class="emphasis"><em>collaborators</em></span> or
          <span class="emphasis"><em>dependencies</em></span>.</p></li><li><p>Other configuration settings to set in the newly created object,
          for example, the number of connections to use in a bean that manages a
          connection pool, or the size limit of the pool.</p></li></ul></div><p>This metadata translates to a set of properties that make up each bean
      definition.</p><div class="table"><a name="beans-factory-bean-definition-tbl"></a><p class="title"><b>Table&nbsp;4.1.&nbsp;The bean definition</b></p><div class="table-contents"><table summary="The bean definition" style="border-collapse: collapse;border-top: 1.0pt solid ; border-bottom: 1.0pt solid ; border-left: 1.0pt solid ; border-right: 1.0pt solid ; "><colgroup><col><col></colgroup><thead><tr><th style="border-right: 1.0pt solid ; border-bottom: 1.0pt solid ; ">Property</th><th style="border-bottom: 1.0pt solid ; ">Explained in...</th></tr></thead><tbody><tr><td style="border-right: 1.0pt solid ; border-bottom: 1.0pt solid ; ">class</td><td style="border-bottom: 1.0pt solid ; "><p> <a class="xref" href="beans.html#beans-factory-class" title="4.3.2&nbsp;Instantiating beans">Section&nbsp;4.3.2, &#8220;Instantiating beans&#8221;</a> </p></td></tr><tr><td style="border-right: 1.0pt solid ; border-bottom: 1.0pt solid ; ">name</td><td style="border-bottom: 1.0pt solid ; "><p> <a class="xref" href="beans.html#beans-beanname" title="4.3.1&nbsp;Naming beans">Section&nbsp;4.3.1, &#8220;Naming beans&#8221;</a> </p></td></tr><tr><td style="border-right: 1.0pt solid ; border-bottom: 1.0pt solid ; ">scope</td><td style="border-bottom: 1.0pt solid ; "><p> <a class="xref" href="beans.html#beans-factory-scopes" title="4.5&nbsp;Bean scopes">Section&nbsp;4.5, &#8220;Bean scopes&#8221;</a> </p></td></tr><tr><td style="border-right: 1.0pt solid ; border-bottom: 1.0pt solid ; ">constructor arguments</td><td style="border-bottom: 1.0pt solid ; "><p> <a class="xref" href="beans.html#beans-factory-collaborators" title="4.4.1&nbsp;Dependency injection">Section&nbsp;4.4.1, &#8220;Dependency injection&#8221;</a>
              </p></td></tr><tr><td style="border-right: 1.0pt solid ; border-bottom: 1.0pt solid ; ">properties</td><td style="border-bottom: 1.0pt solid ; "><p> <a class="xref" href="beans.html#beans-factory-collaborators" title="4.4.1&nbsp;Dependency injection">Section&nbsp;4.4.1, &#8220;Dependency injection&#8221;</a>
              </p></td></tr><tr><td style="border-right: 1.0pt solid ; border-bottom: 1.0pt solid ; ">autowiring mode</td><td style="border-bottom: 1.0pt solid ; "><p> <a class="xref" href="beans.html#beans-factory-autowire" title="4.4.5&nbsp;Autowiring collaborators">Section&nbsp;4.4.5, &#8220;Autowiring collaborators&#8221;</a>
              </p></td></tr><tr><td style="border-right: 1.0pt solid ; border-bottom: 1.0pt solid ; ">lazy-initialization mode</td><td style="border-bottom: 1.0pt solid ; "><p> <a class="xref" href="beans.html#beans-factory-lazy-init" title="4.4.4&nbsp;Lazy-initialized beans">Section&nbsp;4.4.4, &#8220;Lazy-initialized
      beans&#8221;</a>
              </p></td></tr><tr><td style="border-right: 1.0pt solid ; border-bottom: 1.0pt solid ; ">initialization method</td><td style="border-bottom: 1.0pt solid ; "><p> <a class="xref" href="beans.html#beans-factory-lifecycle-initializingbean" title="4.6.1.1&nbsp;Initialization callbacks">Section&nbsp;4.6.1.1, &#8220;Initialization callbacks&#8221;</a>
              </p></td></tr><tr><td style="border-right: 1.0pt solid ; ">destruction method</td><td style=""><p> <a class="xref" href="beans.html#beans-factory-lifecycle-disposablebean" title="4.6.1.2&nbsp;Destruction callbacks">Section&nbsp;4.6.1.2, &#8220;Destruction callbacks&#8221;</a> </p></td></tr></tbody></table></div></div><br class="table-break"><p>In addition to bean definitions that contain information on how to
      create a specific bean, the
      <code class="interfacename">ApplicationContext</code> implementations also
      permit the registration of existing objects that are created outside the
      container, by users. This is done by accessing the ApplicationContext's
      BeanFactory via the method <code class="methodname">getBeanFactory()</code> which
      returns the BeanFactory implementation
      <code class="classname">DefaultListableBeanFactory</code>.
      <code class="classname">DefaultListableBeanFactory</code> supports this
      registration through the methods
      <code class="methodname">registerSingleton(..)</code> and
      <code class="methodname">registerBeanDefinition(..)</code>. However, typical
      applications work solely with beans defined through metadata bean
      definitions.</p><div class="section" lang="en"><div class="titlepage"><div><div><h3 class="title"><a name="beans-beanname"></a>4.3.1&nbsp;Naming beans</h3></div></div></div><p>Every bean has one or more identifiers. These identifiers must be
        unique within the container that hosts the bean. A bean usually has only
        one identifier, but if it requires more than one, the extra ones can be
        considered aliases.</p><p>In XML-based configuration metadata, you use the
        <code class="literal">id</code> and/or <code class="literal">name</code> attributes to
        specify the bean identifier(s). The <code class="literal">id</code> attribute
        allows you to specify exactly one id.  Conventionally these names are
        alphanumeric ('myBean', 'fooService', etc), but may special characters
        as well.  If you want to introduce other aliases to the bean, you can
        also specify them in the <code class="literal">name</code> attribute, separated by
        a comma (<code class="literal">,</code>), semicolon (<code class="literal">;</code>), or
        white space.  As a historical note, in versions prior to Spring 3.1, the
        <code class="literal">id</code> attribute was typed as an
        <code class="literal">xsd:ID</code>, which constrained possible characters.  As of
        3.1, it is now <code class="literal">xsd:string</code>.  Note that bean id
        uniqueness is still enforced by the container, though no longer by XML
        parsers.</p><p>You are not required to supply a name or id for a bean. If no name
        or id is supplied explicitly, the container generates a unique name for
        that bean. However, if you want to refer to that bean by name, through
        the use of the <code class="literal">ref</code> element or <a class="link" href="beans.html#beans-servicelocator" title="4.15.2&nbsp;Glue code and the evil singleton">Service Locator</a> style lookup,
        you must provide a name. Motivations for not supplying a name are
        related to using <a class="link" href="beans.html#beans-inner-beans" title="4.4.2.3&nbsp;Inner beans">inner beans</a>
        and <a class="link" href="beans.html#beans-factory-autowire" title="4.4.5&nbsp;Autowiring collaborators">autowiring
        collaborators</a>.</p><div class="sidebar"><p class="title"><b>Bean naming conventions</b></p><p>The convention is to use the standard Java convention for instance
          field names when naming beans. That is, bean names start with a
          lowercase letter, and are camel-cased from then on. Examples of such
          names would be (without quotes) <code class="literal">'accountManager'</code>,
          <code class="literal">'accountService'</code>, <code class="literal">'userDao'</code>,
          <code class="literal">'loginController'</code>, and so forth.</p><p>Naming beans consistently makes your configuration easier to read
          and understand, and if you are using Spring AOP it helps a lot when
          applying advice to a set of beans related by name.</p></div><div class="section" lang="en"><div class="titlepage"><div><div><h4 class="title"><a name="beans-beanname-alias"></a>4.3.1.1&nbsp;Aliasing a bean outside the bean definition</h4></div></div></div><p>In a bean definition itself, you can supply more than one name for
          the bean, by using a combination of up to one name specified by the
          <code class="literal">id</code> attribute, and any number of other names in the
          <code class="literal">name</code> attribute. These names can be equivalent
          aliases to the same bean, and are useful for some situations, such as
          allowing each component in an application to refer to a common
          dependency by using a bean name that is specific to that component
          itself.</p><p>Specifying all aliases where the bean is actually defined is not
          always adequate, however. It is sometimes desirable to introduce an
          alias for a bean that is defined elsewhere. This is commonly the case
          in large systems where configuration is split amongst each subsystem,
          each subsystem having its own set of object definitions. In XML-based
          configuration metadata, you can use the
          <code class="literal">&lt;alias/&gt;</code> element to accomplish this.</p><pre class="programlisting">&lt;<span class="hl-tag">alias</span> <span class="hl-attribute">name</span>=<span class="hl-value">"fromName"</span> <span class="hl-attribute">alias</span>=<span class="hl-value">"toName"</span>/&gt;</pre><p>In this case, a bean in the same container which is named
          <code class="literal">fromName</code>, may also after the use of this alias
          definition, be referred to as <code class="literal">toName</code>.</p><p>For example, the configuration metadata for subsystem A may refer
          to a DataSource via the name 'subsystemA-dataSource. The configuration
          metadata for subsystem B may refer to a DataSource via the name
          'subsystemB-dataSource'. When composing the main application that uses
          both these subsystems the main application refers to the DataSource
          via the name 'myApp-dataSource'. To have all three names refer to the
          same object you add to the MyApp configuration metadata the following
          aliases definitions:</p><pre class="programlisting">&lt;<span class="hl-tag">alias</span> <span class="hl-attribute">name</span>=<span class="hl-value">"subsystemA-dataSource"</span> <span class="hl-attribute">alias</span>=<span class="hl-value">"subsystemB-dataSource"</span>/&gt;
&lt;<span class="hl-tag">alias</span> <span class="hl-attribute">name</span>=<span class="hl-value">"subsystemA-dataSource"</span> <span class="hl-attribute">alias</span>=<span class="hl-value">"myApp-dataSource"</span> /&gt;</pre><p>Now each component and the main application can refer to the
          dataSource through a name that is unique and guaranteed not to clash
          with any other definition (effectively creating a namespace), yet they
          refer to the same bean.</p></div></div><div class="section" lang="en"><div class="titlepage"><div><div><h3 class="title"><a name="beans-factory-class"></a>4.3.2&nbsp;Instantiating beans</h3></div></div></div><p>A bean definition essentially is a recipe for creating one or more
        objects. The container looks at the recipe for a named bean when asked,
        and uses the configuration metadata encapsulated by that bean definition
        to create (or acquire) an actual object.</p><p>If you use XML-based configuration metadata, you specify the type
        (or class) of object that is to be instantiated in the
        <code class="literal">class</code> attribute of the
        <code class="literal">&lt;bean/&gt;</code> element. This <code class="literal">class</code>
        attribute, which internally is a <code class="classname">Class</code> property
        on a <code class="interfacename">BeanDefinition</code> instance, is usually
        mandatory. (For exceptions, see <a class="xref" href="beans.html#beans-factory-class-instance-factory-method" title="4.3.2.3&nbsp;Instantiation using an instance factory method">Section&nbsp;4.3.2.3, &#8220;Instantiation using an instance factory method&#8221;</a> and <a class="xref" href="beans.html#beans-child-bean-definitions" title="4.7&nbsp;Bean definition inheritance">Section&nbsp;4.7, &#8220;Bean definition inheritance&#8221;</a>.) You use the
        <code class="classname">Class</code> property in one of two ways: </p><div class="itemizedlist"><ul type="disc"><li><p>Typically, to specify the bean class to be constructed in the
            case where the container itself directly creates the bean by calling
            its constructor reflectively, somewhat equivalent to Java code using
            the <code class="code">new</code> operator.</p></li></ul></div><div class="itemizedlist"><ul type="disc"><li><p>To specify the actual class containing the
            <code class="literal">static</code> factory method that will be invoked to
            create the object, in the less common case where the container
            invokes a <code class="literal">static</code>, <span class="emphasis"><em>factory</em></span>
            method on a class to create the bean. The object type returned from
            the invocation of the <code class="literal">static</code> factory method may
            be the same class or another class entirely.</p></li></ul></div><div class="sidebar"><p class="title"><b>Inner class names</b></p><p>If you want to configure a bean definition for a
          <code class="literal">static</code> nested class, you have to use the
          <span class="emphasis"><em>binary</em></span> name of the inner class.</p><p>For example, if you have a class called <code class="classname">Foo</code>
          in the <code class="literal">com.example</code> package, and this
          <code class="classname">Foo</code> class has a <code class="literal">static</code> inner
          class called <code class="classname">Bar</code>, the value of the
          <code class="literal">'class'</code> attribute on a bean definition would
          be...</p><p><code class="classname">com.example.Foo$Bar</code></p><p>Notice the use of the <code class="literal">$</code> character in the name
          to separate the inner class name from the outer class name.</p></div><div class="section" lang="en"><div class="titlepage"><div><div><h4 class="title"><a name="beans-factory-class-ctor"></a>4.3.2.1&nbsp;Instantiation with a constructor</h4></div></div></div><p>When you create a bean by the constructor approach, all normal
          classes are usable by and compatible with Spring. That is, the class
          being developed does not need to implement any specific interfaces or
          to be coded in a specific fashion. Simply specifying the bean class
          should suffice. However, depending on what type of IoC you use for
          that specific bean, you may need a default (empty) constructor.</p><p>The Spring IoC container can manage virtually
          <span class="emphasis"><em>any</em></span> class you want it to manage; it is not
          limited to managing true JavaBeans. Most Spring users prefer actual
          JavaBeans with only a default (no-argument) constructor and
          appropriate setters and getters modeled after the properties in the
          container. You can also have more exotic non-bean-style classes in
          your container. If, for example, you need to use a legacy connection
          pool that absolutely does not adhere to the JavaBean specification,
          Spring can manage it as well.</p><p>With XML-based configuration metadata you can specify your bean
          class as follows:</p><pre class="programlisting">&lt;<span class="hl-tag">bean</span> <span class="hl-attribute">id</span>=<span class="hl-value">"exampleBean"</span> <span class="hl-attribute">class</span>=<span class="hl-value">"examples.ExampleBean"</span>/&gt;

&lt;<span class="hl-tag">bean</span> <span class="hl-attribute">name</span>=<span class="hl-value">"anotherExample"</span> <span class="hl-attribute">class</span>=<span class="hl-value">"examples.ExampleBeanTwo"</span>/&gt;</pre><p>For details about the mechanism for supplying arguments to the
          constructor (if required) and setting object instance properties after
          the object is constructed, see <a class="link" href="beans.html#beans-factory-collaborators" title="4.4.1&nbsp;Dependency injection">Injecting
          Dependencies</a>.</p></div><div class="section" lang="en"><div class="titlepage"><div><div><h4 class="title"><a name="beans-factory-class-static-factory-method"></a>4.3.2.2&nbsp;Instantiation with a static factory method</h4></div></div></div><p>When defining a bean that you create with a static factory method,
          you use the <code class="literal">class</code> attribute to specify the class
          containing the <code class="literal">static</code> factory method and an
          attribute named <code class="literal">factory-method</code> to specify the name
          of the factory method itself. You should be able to call this method
          (with optional arguments as described later) and return a live object,
          which subsequently is treated as if it had been created through a
          constructor. One use for such a bean definition is to call
          <code class="literal">static</code> factories in legacy code.</p><p>The following bean definition specifies that the bean will be
          created by calling a factory-method. The definition does not specify
          the type (class) of the returned object, only the class containing the
          factory method. In this example, the
          <code class="methodname">createInstance()</code> method must be a
          <span class="emphasis"><em>static</em></span> method.</p><pre class="programlisting">&lt;<span class="hl-tag">bean</span> <span class="hl-attribute">id</span>=<span class="hl-value">"clientService"</span>
      <span class="hl-attribute">class</span>=<span class="hl-value">"examples.ClientService"</span>
      <span class="hl-attribute">factory-method</span>=<span class="hl-value">"createInstance"</span>/&gt;</pre><pre class="programlisting"><span class="hl-keyword">public</span> <span class="hl-keyword">class</span> ClientService {
  <span class="hl-keyword">private</span> <span class="hl-keyword">static</span> ClientService clientService = <span class="hl-keyword">new</span> ClientService();
  <span class="hl-keyword">private</span> ClientService() {}

  <span class="hl-keyword">public</span> <span class="hl-keyword">static</span> ClientService createInstance() {
    <span class="hl-keyword">return</span> clientService;
  }
}</pre><p>For details about the mechanism for supplying (optional) arguments
          to the factory method and setting object instance properties after the
          object is returned from the factory, see <a class="link" href="beans.html#beans-factory-properties-detailed" title="4.4.2&nbsp;Dependencies and configuration in detail">Dependencies and
          configuration in detail</a>.</p></div><div class="section" lang="en"><div class="titlepage"><div><div><h4 class="title"><a name="beans-factory-class-instance-factory-method"></a>4.3.2.3&nbsp;Instantiation using an instance factory method</h4></div></div></div><p>Similar to instantiation through a <a class="link" href="beans.html#beans-factory-class-static-factory-method" title="4.3.2.2&nbsp;Instantiation with a static factory method">static factory
          method</a>, instantiation with an instance factory method invokes a
          non-static method of an existing bean from the container to create a
          new bean. To use this mechanism, leave the <code class="literal">class
          </code>attribute empty, and in the <code class="literal">factory-bean</code>
          attribute, specify the name of a bean in the current (or
          parent/ancestor) container that contains the instance method that is
          to be invoked to create the object. Set the name of the factory method
          itself with the <code class="literal">factory-method</code> attribute.</p><pre class="programlisting">&lt;<span class="hl-comment">!-- the factory bean, which contains a method called createInstance() --</span>&gt;
&lt;<span class="hl-tag">bean</span> <span class="hl-attribute">id</span>=<span class="hl-value">"serviceLocator"</span> <span class="hl-attribute">class</span>=<span class="hl-value">"examples.DefaultServiceLocator"</span>&gt;
  &lt;<span class="hl-comment">!-- inject any dependencies required by this locator bean --</span>&gt;
&lt;<span class="hl-tag">/bean</span>&gt;

&lt;<span class="hl-comment">!-- the bean to be created via the factory bean --</span>&gt;
&lt;<span class="hl-tag">bean</span> <span class="hl-attribute">id</span>=<span class="hl-value">"clientService"</span>
      <span class="hl-attribute">factory-bean</span>=<span class="hl-value">"serviceLocator"</span>
      <span class="hl-attribute">factory-method</span>=<span class="hl-value">"createClientServiceInstance"</span>/&gt;</pre><pre class="programlisting"><span class="hl-keyword">public</span> <span class="hl-keyword">class</span> DefaultServiceLocator {
  <span class="hl-keyword">private</span> <span class="hl-keyword">static</span> ClientService clientService = <span class="hl-keyword">new</span> ClientServiceImpl();
  <span class="hl-keyword">private</span> DefaultServiceLocator() {}

  <span class="hl-keyword">public</span> ClientService createClientServiceInstance() {
    <span class="hl-keyword">return</span> clientService;
  }
}</pre><p>One factory class can also hold more than one factory method as
          shown here:</p><pre class="programlisting">
&lt;<span class="hl-tag">bean</span> <span class="hl-attribute">id</span>=<span class="hl-value">"serviceLocator"</span> <span class="hl-attribute">class</span>=<span class="hl-value">"examples.DefaultServiceLocator"</span>&gt;
  &lt;<span class="hl-comment">!-- inject any dependencies required by this locator bean --</span>&gt;
&lt;<span class="hl-tag">/bean</span>&gt;
&lt;<span class="hl-tag">bean</span> <span class="hl-attribute">id</span>=<span class="hl-value">"clientService"</span>
      <span class="hl-attribute">factory-bean</span>=<span class="hl-value">"serviceLocator"</span>
      <span class="hl-attribute">factory-method</span>=<span class="hl-value">"createClientServiceInstance"</span>/&gt;

&lt;<span class="hl-tag">bean</span> <span class="hl-attribute">id</span>=<span class="hl-value">"accountService"</span>
      <span class="hl-attribute">factory-bean</span>=<span class="hl-value">"serviceLocator"</span>
      <span class="hl-attribute">factory-method</span>=<span class="hl-value">"createAccountServiceInstance"</span>/&gt;</pre><pre class="programlisting"><span class="hl-keyword">public</span> <span class="hl-keyword">class</span> DefaultServiceLocator {
  <span class="hl-keyword">private</span> <span class="hl-keyword">static</span> ClientService clientService = <span class="hl-keyword">new</span> ClientServiceImpl();
  <span class="hl-keyword">private</span> <span class="hl-keyword">static</span> AccountService accountService = <span class="hl-keyword">new</span> AccountServiceImpl();

  <span class="hl-keyword">private</span> DefaultServiceLocator() {}

  <span class="hl-keyword">public</span> ClientService createClientServiceInstance() {
    <span class="hl-keyword">return</span> clientService;
  }

  <span class="hl-keyword">public</span> AccountService createAccountServiceInstance() {
    <span class="hl-keyword">return</span> accountService;
  }
}</pre><p>This approach shows that the factory bean itself can be managed
          and configured through dependency injection (DI). See <a class="link" href="beans.html#beans-factory-properties-detailed" title="4.4.2&nbsp;Dependencies and configuration in detail"></a><a class="link" href="beans.html#beans-factory-properties-detailed" title="4.4.2&nbsp;Dependencies and configuration in detail">Dependencies and
          configuration in detail</a><a class="link" href="beans.html#beans-factory-properties-detailed" title="4.4.2&nbsp;Dependencies and configuration in detail">.</a></p><div class="note" style="margin-left: 0.5in; margin-right: 0.5in;"><table border="0" summary="Note"><tr><td rowspan="2" align="center" valign="top" width="25"><img alt="[Note]" src="images/note.gif"></td><th align="left">Note</th></tr><tr><td align="left" valign="top"><p>In Spring documentation,<span class="emphasis"><em> factory bean</em></span>
            refers to a bean that is configured in the Spring container that
            will create objects through an <a class="link" href="beans.html#beans-factory-class-instance-factory-method" title="4.3.2.3&nbsp;Instantiation using an instance factory method">instance</a> or <a class="link" href="beans.html#beans-factory-class-static-factory-method" title="4.3.2.2&nbsp;Instantiation with a static factory method">static</a>
            factory method. By contrast,
            <code class="interfacename">FactoryBean</code> (notice the
            capitalization) refers to a Spring-specific <a class="link" href="beans.html#beans-factory-extension-factorybean" title="4.8.3&nbsp;Customizing instantiation logic with a FactoryBean">
            <code class="interfacename">FactoryBean</code> </a>.</p></td></tr></table></div></div></div></div><div class="section" lang="en"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="beans-dependencies"></a>4.4&nbsp;Dependencies</h2></div></div></div><p>A typical enterprise application does not consist of a single object (or
    bean in the Spring parlance). Even the simplest application has a few
    objects that work together to present what the end-user sees as a coherent
    application. This next section explains how you go from defining a number of
    bean definitions that stand alone to a fully realized application where
    objects collaborate to achieve a goal.</p><div class="section" lang="en"><div class="titlepage"><div><div><h3 class="title"><a name="beans-factory-collaborators"></a>4.4.1&nbsp;Dependency injection</h3></div></div></div><p><span class="emphasis"><em>Dependency injection</em></span> (DI) is a process whereby
      objects define their dependencies, that is, the other objects they work
      with, only through constructor arguments, arguments to a factory method,
      or properties that are set on the object instance after it is constructed
      or returned from a factory method. The container then
      <span class="emphasis"><em>injects</em></span> those dependencies when it creates the bean.
      This process is fundamentally the inverse, hence the name
      <span class="emphasis"><em>Inversion of Control</em></span> (IoC), of the bean itself
      controlling the instantiation or location of its dependencies on its own
      by using direct construction of classes, or the <span class="emphasis"><em>Service
      Locator</em></span> pattern.</p><p>Code is cleaner with the DI principle and decoupling is more effective
      when objects are provided with their dependencies. The object does not
      look up its dependencies, and does not know the location or class of the
      dependencies. As such, your classes become easier to test, in particular
      when the dependencies are on interfaces or abstract base classes, which
      allow for stub or mock implementations to be used in unit tests.</p><p>DI exists in two major variants, <a class="link" href="beans.html#beans-constructor-injection" title="4.4.1.1&nbsp;Constructor-based dependency injection">Constructor-based dependency
      injection</a> and <a class="link" href="beans.html#beans-setter-injection" title="4.4.1.2&nbsp;Setter-based dependency injection">Setter-based
      dependency injection</a>.</p><div class="section" lang="en"><div class="titlepage"><div><div><h4 class="title"><a name="beans-constructor-injection"></a>4.4.1.1&nbsp;Constructor-based dependency injection</h4></div></div></div><p><span class="emphasis"><em>Constructor-based</em></span> DI is accomplished by the
        container invoking a constructor with a number of arguments, each
        representing a dependency. Calling a <code class="literal">static</code> factory
        method with specific arguments to construct the bean is nearly
        equivalent, and this discussion treats arguments to a constructor and to
        a <code class="literal">static</code> factory method similarly. The following
        example shows a class that can only be dependency-injected with
        constructor injection. Notice that there is nothing
        <span class="emphasis"><em>special</em></span> about this class, it is a POJO that has no
        dependencies on container specific interfaces, base classes or
        annotations.</p><pre class="programlisting"><span class="hl-keyword">public</span> <span class="hl-keyword">class</span> SimpleMovieLister {

  <span class="hl-comment">// the SimpleMovieLister has a dependency on a MovieFinder</span>
  <span class="hl-keyword">private</span> MovieFinder movieFinder;

  <span class="hl-comment">// a constructor so that the Spring container can 'inject' a MovieFinder</span>
  <span class="hl-keyword">public</span> SimpleMovieLister(MovieFinder movieFinder) {
      <span class="hl-keyword">this</span>.movieFinder = movieFinder;
  }

  <span class="hl-comment">// business logic that actually 'uses' the injected MovieFinder is omitted...</span>
}</pre><div class="section" lang="en"><div class="titlepage"><div><div><h5 class="title"><a name="beans-factory-ctor-arguments-resolution"></a>Constructor argument resolution</h5></div></div></div><p>Constructor argument resolution matching occurs using the
          argument's type. If no potential ambiguity exists in the constructor
          arguments of a bean definition, then the order in which the
          constructor arguments are defined in a bean definition is the order in
          which those arguments are supplied to the appropriate constructor when
          the bean is being instantiated. Consider the following class:</p><pre class="programlisting"><span class="hl-keyword">package</span> x.y;

<span class="hl-keyword">public</span> <span class="hl-keyword">class</span> Foo {

  <span class="hl-keyword">public</span> Foo(Bar bar, Baz baz) {
      <span class="hl-comment">// ...</span>
  }
}</pre><p>No potential ambiguity exists, assuming that
          <code class="classname">Bar</code> and <code class="classname">Baz</code> classes are
          not related by inheritance. Thus the following configuration works
          fine, and you do not need to specify the constructor argument indexes
          and/or types explicitly in the
          <code class="literal">&lt;constructor-arg/&gt;</code> element.</p><pre class="programlisting">&lt;<span class="hl-tag">beans</span>&gt;
  &lt;<span class="hl-tag">bean</span> <span class="hl-attribute">id</span>=<span class="hl-value">"foo"</span> <span class="hl-attribute">class</span>=<span class="hl-value">"x.y.Foo"</span>&gt;
      &lt;<span class="hl-tag">constructor-arg</span> <span class="hl-attribute">ref</span>=<span class="hl-value">"bar"</span>/&gt;
      &lt;<span class="hl-tag">constructor-arg</span> <span class="hl-attribute">ref</span>=<span class="hl-value">"baz"</span>/&gt;
  &lt;<span class="hl-tag">/bean</span>&gt;

  &lt;<span class="hl-tag">bean</span> <span class="hl-attribute">id</span>=<span class="hl-value">"bar"</span> <span class="hl-attribute">class</span>=<span class="hl-value">"x.y.Bar"</span>/&gt;
  &lt;<span class="hl-tag">bean</span> <span class="hl-attribute">id</span>=<span class="hl-value">"baz"</span> <span class="hl-attribute">class</span>=<span class="hl-value">"x.y.Baz"</span>/&gt;

&lt;<span class="hl-tag">/beans</span>&gt;</pre><p>When another bean is referenced, the type is known, and matching
          can occur (as was the case with the preceding example). When a simple
          type is used, such as
          <code class="literal">&lt;value&gt;true&lt;value&gt;</code>, Spring cannot
          determine the type of the value, and so cannot match by type without
          help. Consider the following class:</p><pre class="programlisting"><span class="hl-keyword">package</span> examples;

<span class="hl-keyword">public</span> <span class="hl-keyword">class</span> ExampleBean {

  <span class="hl-comment">// No. of years to the calculate the Ultimate Answer</span>
  <span class="hl-keyword">private</span> <span class="hl-keyword">int</span> years;

  <span class="hl-comment">// The Answer to Life, the Universe, and Everything</span>
  <span class="hl-keyword">private</span> String ultimateAnswer;

  <span class="hl-keyword">public</span> ExampleBean(<span class="hl-keyword">int</span> years, String ultimateAnswer) {
      <span class="hl-keyword">this</span>.years = years;
      <span class="hl-keyword">this</span>.ultimateAnswer = ultimateAnswer;
  }
}</pre><div class="section" lang="en"><div class="titlepage"><div><div><h6 class="title"><a name="beans-factory-ctor-arguments-type"></a>Constructor argument type matching</h6></div></div></div><p>In the preceding scenario, the container
            <span class="emphasis"><em>can</em></span> use type matching with simple types if you
            explicitly specify the type of the constructor argument using the
            <code class="literal">type</code> attribute. For example:</p><pre class="programlisting">&lt;<span class="hl-tag">bean</span> <span class="hl-attribute">id</span>=<span class="hl-value">"exampleBean"</span> <span class="hl-attribute">class</span>=<span class="hl-value">"examples.ExampleBean"</span>&gt;
&lt;<span class="hl-tag">constructor-arg</span> <span class="hl-attribute">type</span>=<span class="hl-value">"int"</span> <span class="hl-attribute">value</span>=<span class="hl-value">"7500000"</span>/&gt;
&lt;<span class="hl-tag">constructor-arg</span> <span class="hl-attribute">type</span>=<span class="hl-value">"java.lang.String"</span> <span class="hl-attribute">value</span>=<span class="hl-value">"42"</span>/&gt;
&lt;<span class="hl-tag">/bean</span>&gt;</pre></div><div class="section" lang="en"><div class="titlepage"><div><div><h6 class="title"><a name="beans-factory-ctor-arguments-index"></a>Constructor argument index</h6></div></div></div><p>Use the <code class="literal">index</code> attribute to specify explicitly
            the index of constructor arguments. For example:</p><pre class="programlisting">&lt;<span class="hl-tag">bean</span> <span class="hl-attribute">id</span>=<span class="hl-value">"exampleBean"</span> <span class="hl-attribute">class</span>=<span class="hl-value">"examples.ExampleBean"</span>&gt;
&lt;<span class="hl-tag">constructor-arg</span> <span class="hl-attribute">index</span>=<span class="hl-value">"0"</span> <span class="hl-attribute">value</span>=<span class="hl-value">"7500000"</span>/&gt;
&lt;<span class="hl-tag">constructor-arg</span> <span class="hl-attribute">index</span>=<span class="hl-value">"1"</span> <span class="hl-attribute">value</span>=<span class="hl-value">"42"</span>/&gt;
&lt;<span class="hl-tag">/bean</span>&gt;</pre><p>In addition to resolving the ambiguity of multiple simple
            values, specifying an index resolves ambiguity where a constructor
            has two arguments of the same type. Note that the <span class="emphasis"><em>index is
            0 based</em></span>.</p></div><div class="section" lang="en"><div class="titlepage"><div><div><h6 class="title"><a name="beans-factory-ctor-arguments-name"></a>Constructor argument name</h6></div></div></div><p>As of Spring 3.0 you can also use the constructor parameter
          name for value disambiguation:</p><pre class="programlisting">&lt;<span class="hl-tag">bean</span> <span class="hl-attribute">id</span>=<span class="hl-value">"exampleBean"</span> <span class="hl-attribute">class</span>=<span class="hl-value">"examples.ExampleBean"</span>&gt;
&lt;<span class="hl-tag">constructor-arg</span> <span class="hl-attribute">name</span>=<span class="hl-value">"years"</span> <span class="hl-attribute">value</span>=<span class="hl-value">"7500000"</span>/&gt;
&lt;<span class="hl-tag">constructor-arg</span> <span class="hl-attribute">name</span>=<span class="hl-value">"ultimateanswer"</span> <span class="hl-attribute">value</span>=<span class="hl-value">"42"</span>/&gt;
&lt;<span class="hl-tag">/bean</span>&gt;</pre><p>Keep in mind that to make this work out of the box your code
          must be compiled with the debug flag enabled so that Spring can
          look up the parameter name from the constructor. If you can't compile
          your code with debug flag (or don't want to) you can use
          <code class="interfacename"><a class="ulink" href="http://download.oracle.com/javase/6/docs/api/java/beans/ConstructorProperties.html" target="_top">@ConstructorProperties</a></code>
          JDK annotation to explicitly name your constructor arguments. The
          sample class would then have to look as follows:</p><pre class="programlisting"><span class="hl-keyword">package</span> examples;

<span class="hl-keyword">public</span> <span class="hl-keyword">class</span> ExampleBean {

  <span class="hl-comment">// Fields omitted</span>

  @ConstructorProperties({<span class="hl-string">"years"</span>, <span class="hl-string">"ultimateAnswer"</span>})
  <span class="hl-keyword">public</span> ExampleBean(<span class="hl-keyword">int</span> years, String ultimateAnswer) {
      <span class="hl-keyword">this</span>.years = years;
      <span class="hl-keyword">this</span>.ultimateAnswer = ultimateAnswer;
  }
}</pre></div></div></div><div class="section" lang="en"><div class="titlepage"><div><div><h4 class="title"><a name="beans-setter-injection"></a>4.4.1.2&nbsp;Setter-based dependency injection</h4></div></div></div><p><span class="emphasis"><em>Setter-based</em></span> DI is accomplished by the
        container calling setter methods on your beans after invoking a
        no-argument constructor or no-argument <code class="literal">static</code> factory
        method to instantiate your bean.</p><p>The following example shows a class that can only be
        dependency-injected using pure setter injection. This class is
        conventional Java. It is a POJO that has no dependencies on container
        specific interfaces, base classes or annotations.</p><pre class="programlisting"><span class="hl-keyword">public</span> <span class="hl-keyword">class</span> SimpleMovieLister {

  <span class="hl-comment">// the SimpleMovieLister has a dependency on the MovieFinder</span>
  <span class="hl-keyword">private</span> MovieFinder movieFinder;

  <span class="hl-comment">// a setter method so that the Spring container can 'inject' a MovieFinder</span>
  <span class="hl-keyword">public</span> <span class="hl-keyword">void</span> setMovieFinder(MovieFinder movieFinder) {
      <span class="hl-keyword">this</span>.movieFinder = movieFinder;
  }

  <span class="hl-comment">// business logic that actually 'uses' the injected MovieFinder is omitted...</span>
}</pre><p>The <code class="interfacename">ApplicationContext</code> supports
        constructor- and setter-based DI for the beans it manages. It also
        supports setter-based DI after some dependencies are already injected
        through the constructor approach. You configure the dependencies in the
        form of a <code class="interfacename">BeanDefinition</code>, which you use
        with <code class="interfacename">PropertyEditor</code> instances to convert
        properties from one format to another. However, most Spring users do not
        work with these classes directly (programmatically), but rather with an
        XML definition file that is then converted internally into instances of
        these classes, and used to load an entire Spring IoC container
        instance.</p><div class="sidebar"><p class="title"><b>Constructor-based or setter-based DI?</b></p><p>Since you can mix both, Constructor- and Setter-based DI, it is a
          good rule of thumb to use constructor arguments for mandatory
          dependencies and setters for optional dependencies. Note that the use
          of a <a class="link" href="beans.html#beans-required-annotation" title="4.9.1&nbsp;@Required">@Required</a>
          annotation on a setter can be used to make setters required
          dependencies.</p><p>The Spring team generally advocates setter injection, because
          large numbers of constructor arguments can get unwieldy, especially
          when properties are optional. Setter methods also make objects of that
          class amenable to reconfiguration or re-injection later. Management
          through <a class="link" href="jmx.html" title="23.&nbsp;JMX">JMX MBeans</a> is a compelling use
          case.</p><p>Some purists favor constructor-based injection. Supplying all
          object dependencies means that the object is always returned to client
          (calling) code in a totally initialized state. The disadvantage is
          that the object becomes less amenable to reconfiguration and
          re-injection.</p><p>Use the DI that makes the most sense for a particular class.
          Sometimes, when dealing with third-party classes to which you do not
          have the source, the choice is made for you. A legacy class may not
          expose any setter methods, and so constructor injection is the only
          available DI.</p></div></div><div class="section" lang="en"><div class="titlepage"><div><div><h4 class="title"><a name="d0e2647"></a>4.4.1.3&nbsp;Dependency resolution process</h4></div></div></div><p>The container performs bean dependency resolution as follows:</p><div class="orderedlist"><ol type="1"><li><p>The <code class="interfacename">ApplicationContext</code> is created
            and initialized with configuration metadata that describes all the
            beans. Configuration metadata can be specified via XML, Java code or
            annotations.</p></li><li><p>For each bean, its dependencies are expressed in the form of
            properties, constructor arguments, or arguments to the
            static-factory method if you are using that instead of a normal
            constructor. These dependencies are provided to the bean,
            <span class="emphasis"><em>when the bean is actually created</em></span>.</p></li><li><p>Each property or constructor argument is an actual definition of
            the value to set, or a reference to another bean in the
            container.</p></li><li><p>Each property or constructor argument which is a value is
            converted from its specified format to the actual type of that
            property or constructor argument. By default Spring can convert a
            value supplied in string format to all built-in types, such as
            <code class="literal">int</code>, <code class="literal">long</code>,
            <code class="literal">String</code>, <code class="literal">boolean</code>, etc.</p></li></ol></div><p>The Spring container validates the configuration of each bean as the
        container is created, including the validation of whether bean reference
        properties refer to valid beans. However, the bean properties themselves
        are not set until the bean <span class="emphasis"><em>is actually created</em></span>.
        Beans that are singleton-scoped and set to be pre-instantiated (the
        default) are created when the container is created. Scopes are defined
        in <a class="xref" href="beans.html#beans-factory-scopes" title="4.5&nbsp;Bean scopes">Section&nbsp;4.5, &#8220;Bean scopes&#8221;</a> Otherwise, the bean is created
        only when it is requested. Creation of a bean potentially causes a graph
        of beans to be created, as the bean's dependencies and its dependencies'
        dependencies (and so on) are created and assigned.</p><div class="sidebar"><p class="title"><b>Circular dependencies</b></p><p>If you use predominantly constructor injection, it is possible to
          create an unresolvable circular dependency scenario.</p><p>For example: Class A requires an instance of class B through
          constructor injection, and class B requires an instance of class A
          through constructor injection. If you configure beans for classes A
          and B to be injected into each other, the Spring IoC container detects
          this circular reference at runtime, and throws a
          <code class="classname">BeanCurrentlyInCreationException</code>.</p><p>One possible solution is to edit the source code of some classes
          to be configured by setters rather than constructors. Alternatively,
          avoid constructor injection and use setter injection only. In other
          words, although it is not recommended, you can configure circular
          dependencies with setter injection.</p><p>Unlike the <span class="emphasis"><em>typical</em></span> case (with no circular
          dependencies), a circular dependency between bean A and bean B forces
          one of the beans to be injected into the other prior to being fully
          initialized itself (a classic chicken/egg scenario).</p></div><p>You can generally trust Spring to do the right thing. It detects
        configuration problems, such as references to non-existent beans and
        circular dependencies, at container load-time. Spring sets properties
        and resolves dependencies as late as possible, when the bean is actually
        created. This means that a Spring container which has loaded correctly
        can later generate an exception when you request an object if there is a
        problem creating that object or one of its dependencies. For example,
        the bean throws an exception as a result of a missing or invalid
        property. This potentially delayed visibility of some configuration
        issues is why <code class="interfacename">ApplicationContext</code>
        implementations by default pre-instantiate singleton beans. At the cost
        of some upfront time and memory to create these beans before they are
        actually needed, you discover configuration issues when the
        <code class="interfacename">ApplicationContext</code> is created, not later.
        You can still override this default behavior so that singleton beans
        will lazy-initialize, rather than be pre-instantiated.</p><p>If no circular dependencies exist, when one or more collaborating
        beans are being injected into a dependent bean, each collaborating bean
        is <span class="emphasis"><em>totally</em></span> configured prior to being injected into
        the dependent bean. This means that if bean A has a dependency on bean
        B, the Spring IoC container completely configures bean B prior to
        invoking the setter method on bean A. In other words, the bean is
        instantiated (if not a pre-instantiated singleton), its dependencies are
        set, and the relevant lifecycle methods (such as a <a class="link" href="beans.html#beans-factory-lifecycle-initializingbean" title="4.6.1.1&nbsp;Initialization callbacks">configured init
        method</a> or the <a class="link" href="beans.html#beans-factory-lifecycle-initializingbean" title="4.6.1.1&nbsp;Initialization callbacks">IntializingBean
        callback method</a>) are invoked.</p></div><div class="section" lang="en"><div class="titlepage"><div><div><h4 class="title"><a name="beans-some-examples"></a>4.4.1.4&nbsp;Examples of dependency injection</h4></div></div></div><p>The following example uses XML-based configuration metadata for
        setter-based DI. A small part of a Spring XML configuration file
        specifies some bean definitions:</p><pre class="programlisting">&lt;<span class="hl-tag">bean</span> <span class="hl-attribute">id</span>=<span class="hl-value">"exampleBean"</span> <span class="hl-attribute">class</span>=<span class="hl-value">"examples.ExampleBean"</span>&gt;

&lt;<span class="hl-comment">!-- setter injection using the nested &lt;ref/&gt; element --</span>&gt;
&lt;<span class="hl-tag">property</span> <span class="hl-attribute">name</span>=<span class="hl-value">"beanOne"</span>&gt;&lt;<span class="hl-tag">ref</span> <span class="hl-attribute">bean</span>=<span class="hl-value">"anotherExampleBean"</span>/&gt;&lt;<span class="hl-tag">/property</span>&gt;

&lt;<span class="hl-comment">!-- setter injection using the neater 'ref' attribute --</span>&gt;
&lt;<span class="hl-tag">property</span> <span class="hl-attribute">name</span>=<span class="hl-value">"beanTwo"</span> <span class="hl-attribute">ref</span>=<span class="hl-value">"yetAnotherBean"</span>/&gt;
&lt;<span class="hl-tag">property</span> <span class="hl-attribute">name</span>=<span class="hl-value">"integerProperty"</span> <span class="hl-attribute">value</span>=<span class="hl-value">"1"</span>/&gt;
&lt;<span class="hl-tag">/bean</span>&gt;

&lt;<span class="hl-tag">bean</span> <span class="hl-attribute">id</span>=<span class="hl-value">"anotherExampleBean"</span> <span class="hl-attribute">class</span>=<span class="hl-value">"examples.AnotherBean"</span>/&gt;
&lt;<span class="hl-tag">bean</span> <span class="hl-attribute">id</span>=<span class="hl-value">"yetAnotherBean"</span> <span class="hl-attribute">class</span>=<span class="hl-value">"examples.YetAnotherBean"</span>/&gt;</pre><pre class="programlisting"><span class="hl-keyword">public</span> <span class="hl-keyword">class</span> ExampleBean {

  <span class="hl-keyword">private</span> AnotherBean beanOne;
  <span class="hl-keyword">private</span> YetAnotherBean beanTwo;
  <span class="hl-keyword">private</span> <span class="hl-keyword">int</span> i;

  <span class="hl-keyword">public</span> <span class="hl-keyword">void</span> setBeanOne(AnotherBean beanOne) {
      <span class="hl-keyword">this</span>.beanOne = beanOne;
  }

  <span class="hl-keyword">public</span> <span class="hl-keyword">void</span> setBeanTwo(YetAnotherBean beanTwo) {
      <span class="hl-keyword">this</span>.beanTwo = beanTwo;
  }

  <span class="hl-keyword">public</span> <span class="hl-keyword">void</span> setIntegerProperty(<span class="hl-keyword">int</span> i) {
      <span class="hl-keyword">this</span>.i = i;
  }
}</pre><p>In the preceding example, setters are declared to match against the
        properties specified in the XML file. The following example uses
        constructor-based DI:</p><pre class="programlisting">&lt;<span class="hl-tag">bean</span> <span class="hl-attribute">id</span>=<span class="hl-value">"exampleBean"</span> <span class="hl-attribute">class</span>=<span class="hl-value">"examples.ExampleBean"</span>&gt;

&lt;<span class="hl-comment">!-- constructor injection using the nested &lt;ref/&gt; element --</span>&gt;
&lt;<span class="hl-tag">constructor-arg</span>&gt;
  &lt;<span class="hl-tag">ref</span> <span class="hl-attribute">bean</span>=<span class="hl-value">"anotherExampleBean"</span>/&gt;
&lt;<span class="hl-tag">/constructor-arg</span>&gt;

&lt;<span class="hl-comment">!-- constructor injection using the neater 'ref' attribute --</span>&gt;
&lt;<span class="hl-tag">constructor-arg</span> <span class="hl-attribute">ref</span>=<span class="hl-value">"yetAnotherBean"</span>/&gt;

&lt;<span class="hl-tag">constructor-arg</span> <span class="hl-attribute">type</span>=<span class="hl-value">"int"</span> <span class="hl-attribute">value</span>=<span class="hl-value">"1"</span>/&gt;
&lt;<span class="hl-tag">/bean</span>&gt;

&lt;<span class="hl-tag">bean</span> <span class="hl-attribute">id</span>=<span class="hl-value">"anotherExampleBean"</span> <span class="hl-attribute">class</span>=<span class="hl-value">"examples.AnotherBean"</span>/&gt;
&lt;<span class="hl-tag">bean</span> <span class="hl-attribute">id</span>=<span class="hl-value">"yetAnotherBean"</span> <span class="hl-attribute">class</span>=<span class="hl-value">"examples.YetAnotherBean"</span>/&gt;</pre><pre class="programlisting"><span class="hl-keyword">public</span> <span class="hl-keyword">class</span> ExampleBean {

  <span class="hl-keyword">private</span> AnotherBean beanOne;
  <span class="hl-keyword">private</span> YetAnotherBean beanTwo;
  <span class="hl-keyword">private</span> <span class="hl-keyword">int</span> i;

  <span class="hl-keyword">public</span> ExampleBean(
      AnotherBean anotherBean, YetAnotherBean yetAnotherBean, <span class="hl-keyword">int</span> i) {
      <span class="hl-keyword">this</span>.beanOne = anotherBean;
      <span class="hl-keyword">this</span>.beanTwo = yetAnotherBean;
      <span class="hl-keyword">this</span>.i = i;
  }
}</pre><p>The constructor arguments specified in the bean definition will be
        used as arguments to the constructor of the
        <code class="classname">ExampleBean</code>.</p><p>Now consider a variant of this example, where instead of using a
        constructor, Spring is told to call a <code class="literal">static</code> factory
        method to return an instance of the object:</p><pre class="programlisting">&lt;<span class="hl-tag">bean</span> <span class="hl-attribute">id</span>=<span class="hl-value">"exampleBean"</span> <span class="hl-attribute">class</span>=<span class="hl-value">"examples.ExampleBean"</span>
    <span class="hl-attribute">factory-method</span>=<span class="hl-value">"createInstance"</span>&gt;
&lt;<span class="hl-tag">constructor-arg</span> <span class="hl-attribute">ref</span>=<span class="hl-value">"anotherExampleBean"</span>/&gt;
&lt;<span class="hl-tag">constructor-arg</span> <span class="hl-attribute">ref</span>=<span class="hl-value">"yetAnotherBean"</span>/&gt;
&lt;<span class="hl-tag">constructor-arg</span> <span class="hl-attribute">value</span>=<span class="hl-value">"1"</span>/&gt;
&lt;<span class="hl-tag">/bean</span>&gt;

&lt;<span class="hl-tag">bean</span> <span class="hl-attribute">id</span>=<span class="hl-value">"anotherExampleBean"</span> <span class="hl-attribute">class</span>=<span class="hl-value">"examples.AnotherBean"</span>/&gt;
&lt;<span class="hl-tag">bean</span> <span class="hl-attribute">id</span>=<span class="hl-value">"yetAnotherBean"</span> <span class="hl-attribute">class</span>=<span class="hl-value">"examples.YetAnotherBean"</span>/&gt;</pre><pre class="programlisting"><span class="hl-keyword">public</span> <span class="hl-keyword">class</span> ExampleBean {

  <span class="hl-comment">// a private constructor</span>
  <span class="hl-keyword">private</span> ExampleBean(...) {
    ...
  }
  
  <span class="hl-comment">// a static factory method; the arguments to this method can be</span>
  <span class="hl-comment">// considered the dependencies of the bean that is returned,</span>
  <span class="hl-comment">// regardless of how those arguments are actually used.</span>
  <span class="hl-keyword">public</span> <span class="hl-keyword">static</span> ExampleBean createInstance (
          AnotherBean anotherBean, YetAnotherBean yetAnotherBean, <span class="hl-keyword">int</span> i) {

      ExampleBean eb = <span class="hl-keyword">new</span> ExampleBean (...);
      <span class="hl-comment">// some other operations...</span>
      <span class="hl-keyword">return</span> eb;
  }
}</pre><p>Arguments to the <code class="literal">static</code> factory method are
        supplied via <code class="literal">&lt;constructor-arg/&gt;</code> elements,
        exactly the same as if a constructor had actually been used. The type of
        the class being returned by the factory method does not have to be of
        the same type as the class that contains the <code class="literal">static</code>
        factory method, although in this example it is. An instance (non-static)
        factory method would be used in an essentially identical fashion (aside
        from the use of the <code class="literal">factory-bean</code> attribute instead of
        the <code class="literal">class</code> attribute), so details will not be
        discussed here.</p></div></div><div class="section" lang="en"><div class="titlepage"><div><div><h3 class="title"><a name="beans-factory-properties-detailed"></a>4.4.2&nbsp;Dependencies and configuration in detail</h3></div></div></div><p>As mentioned in the previous section, you can define bean properties
      and constructor arguments as references to other managed beans
      (collaborators), or as values defined inline. Spring's XML-based
      configuration metadata supports sub-element types within its
      <code class="literal">&lt;property/&gt;</code> and
      <code class="literal">&lt;constructor-arg/&gt;</code> elements for this
      purpose.</p><div class="section" lang="en"><div class="titlepage"><div><div><h4 class="title"><a name="beans-value-element"></a>4.4.2.1&nbsp;Straight values (primitives, <code class="literal">Strings</code>, and so
        on)</h4></div></div></div><p>The <code class="literal">value</code> attribute of the
        <code class="literal">&lt;property/&gt;</code> element specifies a property or
        constructor argument as a human-readable string representation. <a class="link" href="validation.html#beans-beans-conversion" title="6.4.2&nbsp;Built-in PropertyEditor implementations">As mentioned previously</a>,
        JavaBeans <code class="literal">PropertyEditors</code> are used to convert these
        string values from a <code class="classname">String</code> to the actual type of
        the property or argument.</p><pre class="programlisting">&lt;<span class="hl-tag">bean</span> <span class="hl-attribute">id</span>=<span class="hl-value">"myDataSource"</span> <span class="hl-attribute">class</span>=<span class="hl-value">"org.apache.commons.dbcp.BasicDataSource"</span> <span class="hl-attribute">destroy-method</span>=<span class="hl-value">"close"</span>&gt;

&lt;<span class="hl-comment">!-- results in a setDriverClassName(String) call --</span>&gt;
&lt;<span class="hl-tag">property</span> <span class="hl-attribute">name</span>=<span class="hl-value">"driverClassName"</span> <span class="hl-attribute">value</span>=<span class="hl-value">"com.mysql.jdbc.Driver"</span>/&gt;
&lt;<span class="hl-tag">property</span> <span class="hl-attribute">name</span>=<span class="hl-value">"url"</span> <span class="hl-attribute">value</span>=<span class="hl-value">"jdbc:mysql://localhost:3306/mydb"</span>/&gt;
&lt;<span class="hl-tag">property</span> <span class="hl-attribute">name</span>=<span class="hl-value">"username"</span> <span class="hl-attribute">value</span>=<span class="hl-value">"root"</span>/&gt;
&lt;<span class="hl-tag">property</span> <span class="hl-attribute">name</span>=<span class="hl-value">"password"</span> <span class="hl-attribute">value</span>=<span class="hl-value">"masterkaoli"</span>/&gt;
&lt;<span class="hl-tag">/bean</span>&gt;</pre><p>The following example uses the <a class="link" href="beans.html#beans-p-namespace" title="4.4.2.6&nbsp;XML shortcut with the p-namespace">p-namespace</a> for even more succinct XML configuration.</p><pre class="programlisting">&lt;<span class="hl-tag">beans</span> <span class="hl-attribute">xmlns</span>=<span class="hl-value">"http://www.springframework.org/schema/beans"</span>
     <span class="hl-attribute">xmlns:xsi</span>=<span class="hl-value">"http://www.w3.org/2001/XMLSchema-instance"</span>
     <span class="hl-attribute">xmlns:p</span>=<span class="hl-value">"http://www.springframework.org/schema/p"</span>
     <span class="hl-attribute">xsi:schemaLocation</span>=<span class="hl-value">"http://www.springframework.org/schema/beans
     http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"</span>&gt;

&lt;<span class="hl-tag">bean</span> <span class="hl-attribute">id</span>=<span class="hl-value">"myDataSource"</span> <span class="hl-attribute">class</span>=<span class="hl-value">"org.apache.commons.dbcp.BasicDataSource"</span>
      <span class="hl-attribute">destroy-method</span>=<span class="hl-value">"close"</span>
      <span class="hl-attribute">p:driverClassName</span>=<span class="hl-value">"com.mysql.jdbc.Driver"</span>
      <span class="hl-attribute">p:url</span>=<span class="hl-value">"jdbc:mysql://localhost:3306/mydb"</span>
      <span class="hl-attribute">p:username</span>=<span class="hl-value">"root"</span>
      <span class="hl-attribute">p:password</span>=<span class="hl-value">"masterkaoli"</span>/&gt;

&lt;<span class="hl-tag">/beans</span>&gt;

</pre><p>The preceding XML is more succinct; however, typos are discovered at
        runtime rather than design time, unless you use an IDE such as <a class="ulink" href="http://www.jetbrains.com/idea/" target="_top">IntelliJ IDEA</a> or the <a class="ulink" href="http://www.springsource.com/products/sts" target="_top">SpringSource Tool
        Suite</a> (STS) that support automatic property completion when you
        create bean definitions. Such IDE assistance is highly
        recommended.</p><p>You can also configure a <code class="classname">java.util.Properties</code>
        instance as:</p><pre class="programlisting">&lt;<span class="hl-tag">bean</span> <span class="hl-attribute">id</span>=<span class="hl-value">"mappings"</span>
    <span class="hl-attribute">class</span>=<span class="hl-value">"org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"</span>&gt;

 &lt;<span class="hl-comment">!-- typed as a java.util.Properties --</span>&gt;
 &lt;<span class="hl-tag">property</span> <span class="hl-attribute">name</span>=<span class="hl-value">"properties"</span>&gt;
    &lt;<span class="hl-tag">value</span>&gt;
       jdbc.driver.className=com.mysql.jdbc.Driver
       jdbc.url=jdbc:mysql://localhost:3306/mydb
    &lt;<span class="hl-tag">/value</span>&gt;
 &lt;<span class="hl-tag">/property</span>&gt;
&lt;<span class="hl-tag">/bean</span>&gt;</pre><p>The Spring container converts the text inside the
        <code class="literal">&lt;value/&gt;</code> element into a
        <code class="classname">java.util.Properties</code> instance by using the
        JavaBeans <code class="interfacename">PropertyEditor</code> mechanism. This
        is a nice shortcut, and is one of a few places where the Spring team do
        favor the use of the nested <code class="literal">&lt;value/&gt;</code> element
        over the <code class="literal">value</code> attribute style.</p><div class="section" lang="en"><div class="titlepage"><div><div><h5 class="title"><a name="beans-idref-element"></a>The <code class="literal">idref</code> element</h5></div></div></div><p>The <code class="literal">idref</code> element is simply an error-proof way
          to pass the <span class="emphasis"><em>id</em></span> (string value - not a reference)
          of another bean in the container to a
          <code class="literal">&lt;constructor-arg/&gt;</code> or
          <code class="literal">&lt;property/&gt;</code> element.</p><pre class="programlisting">&lt;<span class="hl-tag">bean</span> <span class="hl-attribute">id</span>=<span class="hl-value">"theTargetBean"</span> <span class="hl-attribute">class</span>=<span class="hl-value">"..."</span>/&gt;

&lt;<span class="hl-tag">bean</span> <span class="hl-attribute">id</span>=<span class="hl-value">"theClientBean"</span> <span class="hl-attribute">class</span>=<span class="hl-value">"..."</span>&gt;
  &lt;<span class="hl-tag">property</span> <span class="hl-attribute">name</span>=<span class="hl-value">"targetName"</span>&gt;
      &lt;<span class="hl-tag">idref</span> <span class="hl-attribute">bean</span>=<span class="hl-value">"theTargetBean"</span> /&gt;
  &lt;<span class="hl-tag">/property</span>&gt;
&lt;<span class="hl-tag">/bean</span>&gt;</pre><p>The above bean definition snippet is <span class="emphasis"><em>exactly</em></span>
          equivalent (at runtime) to the following snippet:</p><pre class="programlisting">&lt;<span class="hl-tag">bean</span> <span class="hl-attribute">id</span>=<span class="hl-value">"theTargetBean"</span> <span class="hl-attribute">class</span>=<span class="hl-value">"..."</span> /&gt;

&lt;<span class="hl-tag">bean</span> <span class="hl-attribute">id</span>=<span class="hl-value">"client"</span> <span class="hl-attribute">class</span>=<span class="hl-value">"..."</span>&gt;
  &lt;<span class="hl-tag">property</span> <span class="hl-attribute">name</span>=<span class="hl-value">"targetName"</span> <span class="hl-attribute">value</span>=<span class="hl-value">"theTargetBean"</span> /&gt;
&lt;<span class="hl-tag">/bean</span>&gt;</pre><p>The first form is preferable to the second, because using the
          <code class="literal">idref</code> tag allows the container to validate
          <span class="emphasis"><em>at deployment time</em></span> that the referenced, named
          bean actually exists. In the second variation, no validation is
          performed on the value that is passed to the
          <code class="literal">targetName</code> property of the
          <code class="literal">client</code> bean. Typos are only discovered (with most
          likely fatal results) when the <code class="literal">client</code> bean is
          actually instantiated. If the <code class="literal">client</code> bean is a
          <a class="link" href="beans.html#beans-factory-scopes" title="4.5&nbsp;Bean scopes">prototype</a> bean, this typo
          and the resulting exception may only be discovered long after the
          container is deployed.</p><p>Additionally, if the referenced bean is in the same XML unit, and
          the bean name is the bean <span class="emphasis"><em>id</em></span>, you can use the
          <code class="literal">local</code> attribute, which allows the XML parser itself
          to validate the bean id earlier, at XML document parse time.</p><pre class="programlisting">&lt;<span class="hl-tag">property</span> <span class="hl-attribute">name</span>=<span class="hl-value">"targetName"</span>&gt;
 &lt;<span class="hl-comment">!-- a bean with id 'theTargetBean' must exist; otherwise an exception will be thrown --</span>&gt;
 &lt;<span class="hl-tag">idref</span> <span class="hl-attribute">local</span>=<span class="hl-value">"theTargetBean"</span>/&gt;
&lt;<span class="hl-tag">/property</span>&gt;</pre><p>A common place (at least in versions earlier than Spring 2.0)
          where the &lt;idref/&gt; element brings value is in the configuration
          of <a class="link" href="aop-api.html#aop-pfb-1" title="9.5.1&nbsp;Basics">AOP interceptors</a> in a
          <code class="classname">ProxyFactoryBean</code> bean definition. Using
          &lt;idref/&gt; elements when you specify the interceptor names
          prevents you from misspelling an interceptor id.</p></div></div><div class="section" lang="en"><div class="titlepage"><div><div><h4 class="title"><a name="beans-ref-element"></a>4.4.2.2&nbsp;References to other beans (collaborators)</h4></div></div></div><p>The <code class="literal">ref</code> element is the final element inside a
        <code class="literal">&lt;constructor-arg/&gt;</code> or
        <code class="literal">&lt;property/&gt;</code> definition element. Here you set
        the value of the specified property of a bean to be a reference to
        another bean (a collaborator) managed by the container. The referenced
        bean is a dependency of the bean whose property will be set, and it is
        initialized on demand as needed before the property is set. (If the
        collaborator is a singleton bean, it may be initialized already by the
        container.) All references are ultimately a reference to another object.
        Scoping and validation depend on whether you specify the id/name of the
        other object through the
        <code class="literal">bean,<code class="literal">local,</code></code> or
        <code class="literal">parent</code> attributes.</p><p>Specifying the target bean through the <code class="literal">bean</code>
        attribute of the <code class="literal">&lt;ref/&gt;</code> tag is the most general
        form, and allows creation of a reference to any bean in the same
        container or parent container, regardless of whether it is in the same
        XML file. The value of the <code class="literal">bean</code> attribute may be the
        same as the <code class="literal">id</code> attribute of the target bean, or as
        one of the values in the <code class="literal">name</code> attribute of the target
        bean.</p><pre class="programlisting">&lt;<span class="hl-tag">ref</span> <span class="hl-attribute">bean</span>=<span class="hl-value">"someBean"</span>/&gt;</pre><p>Specifying the target bean through the <code class="literal">local</code>
        attribute leverages the ability of the XML parser to validate XML id
        references within the same file. The value of the
        <code class="literal">local</code> attribute must be the same as the
        <code class="literal">id</code> attribute of the target bean. The XML parser
        issues an error if no matching element is found in the same file. As
        such, using the local variant is the best choice (in order to know about
        errors as early as possible) if the target bean is in the same XML
        file.</p><pre class="programlisting">&lt;<span class="hl-tag">ref</span> <span class="hl-attribute">local</span>=<span class="hl-value">"someBean"</span>/&gt;</pre><p>Specifying the target bean through the <code class="literal">parent</code>
        attribute creates a reference to a bean that is in a parent container of
        the current container. The value of the <code class="literal">parent</code>
        attribute may be the same as either the <code class="literal">id</code> attribute
        of the target bean, or one of the values in the <code class="literal">name</code>
        attribute of the target bean, and the target bean must be in a parent
        container of the current one. You use this bean reference variant mainly
        when you have a hierarchy of containers and you want to wrap an existing
        bean in a parent container with a proxy that will have the same name as
        the parent bean.</p><pre class="programlisting">&lt;<span class="hl-comment">!-- in the parent context --</span>&gt;
&lt;<span class="hl-tag">bean</span> <span class="hl-attribute">id</span>=<span class="hl-value">"accountService"</span> <span class="hl-attribute">class</span>=<span class="hl-value">"com.foo.SimpleAccountService"</span>&gt;
  &lt;<span class="hl-comment">!-- insert dependencies as required as here --</span>&gt;
&lt;<span class="hl-tag">/bean</span>&gt;</pre><pre class="programlisting">&lt;<span class="hl-comment">!-- in the child (descendant) context --</span>&gt;
&lt;<span class="hl-tag">bean</span> <span class="hl-attribute">id</span>=<span class="hl-value">"accountService"</span>  <span class="hl-attribute">&lt;--</span> <span class="hl-attribute">bean</span> <span class="hl-attribute">name</span> <span class="hl-attribute">is</span> <span class="hl-attribute">the</span> <span class="hl-attribute">same</span> <span class="hl-attribute">as</span> <span class="hl-attribute">the</span> <span class="hl-attribute">parent</span> <span class="hl-attribute">bean</span> <span class="hl-attribute">--&gt;</span>
    <span class="hl-attribute">class</span>=<span class="hl-value">"org.springframework.aop.framework.ProxyFactoryBean"</span>&gt;
    &lt;<span class="hl-tag">property</span> <span class="hl-attribute">name</span>=<span class="hl-value">"target"</span>&gt;
        &lt;<span class="hl-tag">ref</span> <span class="hl-attribute">parent</span>=<span class="hl-value">"accountService"</span>/&gt;  &lt;<span class="hl-comment">!-- notice how we refer to the parent bean --</span>&gt;
    &lt;<span class="hl-tag">/property</span>&gt;
  &lt;<span class="hl-comment">!-- insert other configuration and dependencies as required here --</span>&gt;
&lt;<span class="hl-tag">/bean</span>&gt;</pre></div><div class="section" lang="en"><div class="titlepage"><div><div><h4 class="title"><a name="beans-inner-beans"></a>4.4.2.3&nbsp;Inner beans</h4></div></div></div><p>A <code class="literal">&lt;bean/&gt;</code> element inside the
        <code class="literal">&lt;property/&gt;</code> or
        <code class="literal">&lt;constructor-arg/&gt;</code> elements defines a so-called
        <em class="firstterm">inner bean</em>.</p><pre class="programlisting">&lt;<span class="hl-tag">bean</span> <span class="hl-attribute">id</span>=<span class="hl-value">"outer"</span> <span class="hl-attribute">class</span>=<span class="hl-value">"..."</span>&gt;
&lt;<span class="hl-comment">!-- instead of using a reference to a target bean, simply define the target bean inline --</span>&gt;
&lt;<span class="hl-tag">property</span> <span class="hl-attribute">name</span>=<span class="hl-value">"target"</span>&gt;
  &lt;<span class="hl-tag">bean</span> <span class="hl-attribute">class</span>=<span class="hl-value">"com.example.Person"</span>&gt; &lt;<span class="hl-comment">!-- this is the inner bean --</span>&gt;
    &lt;<span class="hl-tag">property</span> <span class="hl-attribute">name</span>=<span class="hl-value">"name"</span> <span class="hl-attribute">value</span>=<span class="hl-value">"Fiona Apple"</span>/&gt;
    &lt;<span class="hl-tag">property</span> <span class="hl-attribute">name</span>=<span class="hl-value">"age"</span> <span class="hl-attribute">value</span>=<span class="hl-value">"25"</span>/&gt;
  &lt;<span class="hl-tag">/bean</span>&gt;
&lt;<span class="hl-tag">/property</span>&gt;
&lt;<span class="hl-tag">/bean</span>&gt;</pre><p>An inner bean definition does not require a defined id or name; the
        container ignores these values. It also ignores the
        <code class="literal">scope</code> flag. Inner beans are
        <span class="emphasis"><em>always</em></span> anonymous and they are
        <span class="emphasis"><em>always</em></span> scoped as <a class="link" href="beans.html#beans-factory-scopes-prototype" title="4.5.2&nbsp;The prototype scope">prototypes</a>. It is
        <span class="emphasis"><em>not</em></span> possible to inject inner beans into
        collaborating beans other than into the enclosing bean.</p></div><div class="section" lang="en"><div class="titlepage"><div><div><h4 class="title"><a name="beans-collection-elements"></a>4.4.2.4&nbsp;Collections</h4></div></div></div><p>In the <code class="literal">&lt;list/&gt;</code>,
        <code class="literal">&lt;set/&gt;</code>, <code class="literal">&lt;map/&gt;</code>, and
        <code class="literal">&lt;props/&gt;</code> elements, you set the properties and
        arguments of the Java <code class="interfacename">Collection</code> types
        <code class="interfacename">List</code>, <code class="interfacename">Set</code>,
        <code class="interfacename">Map</code>, and
        <code class="interfacename">Properties</code>, respectively.</p><pre class="programlisting">&lt;<span class="hl-tag">bean</span> <span class="hl-attribute">id</span>=<span class="hl-value">"moreComplexObject"</span> <span class="hl-attribute">class</span>=<span class="hl-value">"example.ComplexObject"</span>&gt;
&lt;<span class="hl-comment">!-- results in a setAdminEmails(java.util.Properties) call --</span>&gt;
&lt;<span class="hl-tag">property</span> <span class="hl-attribute">name</span>=<span class="hl-value">"adminEmails"</span>&gt;
  &lt;<span class="hl-tag">props</span>&gt;
      &lt;<span class="hl-tag">prop</span> <span class="hl-attribute">key</span>=<span class="hl-value">"administrator"</span>&gt;administrator@example.org&lt;<span class="hl-tag">/prop</span>&gt;
      &lt;<span class="hl-tag">prop</span> <span class="hl-attribute">key</span>=<span class="hl-value">"support"</span>&gt;support@example.org&lt;<span class="hl-tag">/prop</span>&gt;
      &lt;<span class="hl-tag">prop</span> <span class="hl-attribute">key</span>=<span class="hl-value">"development"</span>&gt;development@example.org&lt;<span class="hl-tag">/prop</span>&gt;
  &lt;<span class="hl-tag">/props</span>&gt;
&lt;<span class="hl-tag">/property</span>&gt;
&lt;<span class="hl-comment">!-- results in a setSomeList(java.util.List) call --</span>&gt;
&lt;<span class="hl-tag">property</span> <span class="hl-attribute">name</span>=<span class="hl-value">"someList"</span>&gt;
  &lt;<span class="hl-tag">list</span>&gt;
      &lt;<span class="hl-tag">value</span>&gt;a list element followed by a reference&lt;<span class="hl-tag">/value</span>&gt;
      &lt;<span class="hl-tag">ref</span> <span class="hl-attribute">bean</span>=<span class="hl-value">"myDataSource"</span> /&gt;
  &lt;<span class="hl-tag">/list</span>&gt;
&lt;<span class="hl-tag">/property</span>&gt;
&lt;<span class="hl-comment">!-- results in a setSomeMap(java.util.Map) call --</span>&gt;
&lt;<span class="hl-tag">property</span> <span class="hl-attribute">name</span>=<span class="hl-value">"someMap"</span>&gt;
  &lt;<span class="hl-tag">map</span>&gt;
      &lt;<span class="hl-tag">entry</span> <span class="hl-attribute">key</span>=<span class="hl-value">"an entry"</span> <span class="hl-attribute">value</span>=<span class="hl-value">"just some string"</span>/&gt;
      &lt;<span class="hl-tag">entry</span> <span class="hl-attribute">key</span> =<span class="hl-value">"a ref"</span> <span class="hl-attribute">value-ref</span>=<span class="hl-value">"myDataSource"</span>/&gt;
  &lt;<span class="hl-tag">/map</span>&gt;
&lt;<span class="hl-tag">/property</span>&gt;
&lt;<span class="hl-comment">!-- results in a setSomeSet(java.util.Set) call --</span>&gt;
&lt;<span class="hl-tag">property</span> <span class="hl-attribute">name</span>=<span class="hl-value">"someSet"</span>&gt;
  &lt;<span class="hl-tag">set</span>&gt;
      &lt;<span class="hl-tag">value</span>&gt;just some string&lt;<span class="hl-tag">/value</span>&gt;
      &lt;<span class="hl-tag">ref</span> <span class="hl-attribute">bean</span>=<span class="hl-value">"myDataSource"</span> /&gt;
  &lt;<span class="hl-tag">/set</span>&gt;
&lt;<span class="hl-tag">/property</span>&gt;
&lt;<span class="hl-tag">/bean</span>&gt;</pre><p><span class="emphasis"><em>The value of a map key or value, or a set value, can also
        again be any of the following elements:</em></span></p><pre class="programlisting">bean | ref | idref | list | set | map | props | value | null</pre><div class="section" lang="en"><div class="titlepage"><div><div><h5 class="title"><a name="beans-collection-elements-merging"></a>Collection merging</h5></div></div></div><p>As of Spring 2.0, the container supports the
          <span class="emphasis"><em>merging</em></span> of collections. An application developer
          can define a parent-style <code class="literal">&lt;list/&gt;</code>,
          <code class="literal">&lt;map/&gt;</code>, <code class="literal">&lt;set/&gt;</code> or
          <code class="literal">&lt;props/&gt;</code> element, and have child-style
          <code class="literal">&lt;list/&gt;</code>, <code class="literal">&lt;map/&gt;</code>,
          <code class="literal">&lt;set/&gt;</code> or <code class="literal">&lt;props/&gt;</code>
          elements inherit and override values from the parent collection. That
          is, the child collection's values are the result of merging the
          elements of the parent and child collections, with the child's
          collection elements overriding values specified in the parent
          collection.</p><p><span class="emphasis"><em>This section on merging discusses the parent-child bean
          mechanism. Readers unfamiliar with parent and child bean definitions
          may wish to read the <a class="link" href="beans.html#beans-child-bean-definitions" title="4.7&nbsp;Bean definition inheritance">relevant section</a> before continuing.</em></span></p><p>The following example demonstrates collection merging:</p><pre class="programlisting">&lt;<span class="hl-tag">beans</span>&gt;
&lt;<span class="hl-tag">bean</span> <span class="hl-attribute">id</span>=<span class="hl-value">"parent"</span> <span class="hl-attribute">abstract</span>=<span class="hl-value">"true"</span> <span class="hl-attribute">class</span>=<span class="hl-value">"example.ComplexObject"</span>&gt;
  &lt;<span class="hl-tag">property</span> <span class="hl-attribute">name</span>=<span class="hl-value">"adminEmails"</span>&gt;
      &lt;<span class="hl-tag">props</span>&gt;
          &lt;<span class="hl-tag">prop</span> <span class="hl-attribute">key</span>=<span class="hl-value">"administrator"</span>&gt;administrator@example.com&lt;<span class="hl-tag">/prop</span>&gt;
          &lt;<span class="hl-tag">prop</span> <span class="hl-attribute">key</span>=<span class="hl-value">"support"</span>&gt;support@example.com&lt;<span class="hl-tag">/prop</span>&gt;
      &lt;<span class="hl-tag">/props</span>&gt;
  &lt;<span class="hl-tag">/property</span>&gt;
&lt;<span class="hl-tag">/bean</span>&gt;
&lt;<span class="hl-tag">bean</span> <span class="hl-attribute">id</span>=<span class="hl-value">"child"</span> <span class="hl-attribute">parent</span>=<span class="hl-value">"parent"</span>&gt;
  &lt;<span class="hl-tag">property</span> <span class="hl-attribute">name</span>=<span class="hl-value">"adminEmails"</span>&gt;
      &lt;<span class="hl-comment">!-- the merge is specified on the *child* collection definition --</span>&gt;
      &lt;<span class="hl-tag">props</span> <span class="hl-attribute">merge</span>=<span class="hl-value">"true"</span>&gt;
          &lt;<span class="hl-tag">prop</span> <span class="hl-attribute">key</span>=<span class="hl-value">"sales"</span>&gt;sales@example.com&lt;<span class="hl-tag">/prop</span>&gt;
          &lt;<span class="hl-tag">prop</span> <span class="hl-attribute">key</span>=<span class="hl-value">"support"</span>&gt;support@example.co.uk&lt;<span class="hl-tag">/prop</span>&gt;
      &lt;<span class="hl-tag">/props</span>&gt;
  &lt;<span class="hl-tag">/property</span>&gt;
&lt;<span class="hl-tag">/bean</span>&gt;
&lt;<span class="hl-tag">beans</span>&gt;</pre><p>Notice the use of the <code class="literal">merge=true</code> attribute on
          the <code class="literal">&lt;props/&gt;</code> element of the
          <code class="literal">adminEmails</code> property of the
          <code class="literal">child</code> bean definition. When the
          <code class="literal">child</code> bean is resolved and instantiated by the
          container, the resulting instance has an
          <code class="literal">adminEmails</code> <code class="classname">Properties</code>
          collection that contains the result of the merging of the child's
          <code class="literal">adminEmails</code> collection with the parent's
          <code class="literal">adminEmails</code> collection.</p><pre class="programlisting">administrator=administrator@example.com
sales=sales@example.com
support=support@example.co.uk</pre><p>The child <code class="classname">Properties</code> collection's value set
          inherits all property elements from the parent
          <code class="literal">&lt;props/&gt;</code>, and the child's value for the
          <code class="literal">support</code> value overrides the value in the parent
          collection.</p><p>This merging behavior applies similarly to the
          <code class="literal">&lt;list/&gt;</code>, <code class="literal">&lt;map/&gt;</code>, and
          <code class="literal">&lt;set/&gt;</code> collection types. In the specific case
          of the <code class="literal">&lt;list/&gt;</code> element, the semantics
          associated with the <code class="classname">List</code> collection type, that
          is, the notion of an <code class="literal">ordered</code> collection of values,
          is maintained; the parent's values precede all of the child list's
          values. In the case of the <code class="interfacename">Map</code>,
          <code class="interfacename">Set</code>, and
          <code class="interfacename">Properties</code> collection types, no
          ordering exists. Hence no ordering semantics are in effect for the
          collection types that underlie the associated
          <code class="interfacename">Map</code>,
          <code class="interfacename">Set</code>, and
          <code class="interfacename">Properties</code> implementation types that
          the container uses internally.</p></div><div class="section" lang="en"><div class="titlepage"><div><div><h5 class="title"><a name="d0e3278"></a>Limitations of collection merging</h5></div></div></div><p>You cannot merge different collection types (such as a
          <code class="interfacename">Map</code> and a
          <code class="interfacename">List</code>), and if you do attempt to do so
          an appropriate <code class="classname">Exception</code> is thrown. The
          <code class="literal">merge</code> attribute must be specified on the lower,
          inherited, child definition; specifying the <code class="literal">merge</code>
          attribute on a parent collection definition is redundant and will not
          result in the desired merging. The merging feature is available only
          in Spring 2.0 and later.</p></div><div class="section" lang="en"><div class="titlepage"><div><div><h5 class="title"><a name="beans-collection-elements-strongly-typed"></a>Strongly-typed collection (Java 5+ only)</h5></div></div></div><p>In Java 5 and later, you can use strongly typed collections (using
          generic types). That is, it is possible to declare a
          <code class="interfacename">Collection</code> type such that it can only
          contain <code class="classname">String</code> elements (for example). If you
          are using Spring to dependency-inject a strongly-typed
          <code class="interfacename">Collection</code> into a bean, you can take
          advantage of Spring's type-conversion support such that the elements
          of your strongly-typed <code class="interfacename">Collection</code>
          instances are converted to the appropriate type prior to being added
          to the <code class="interfacename">Collection</code>.</p><pre class="programlisting"><span class="hl-keyword">public</span> <span class="hl-keyword">class</span> Foo {

  <span class="hl-keyword">private</span> Map&lt;String, Float&gt; accounts;

  <span class="hl-keyword">public</span> <span class="hl-keyword">void</span> setAccounts(Map&lt;String, Float&gt; accounts) {
      <span class="hl-keyword">this</span>.accounts = accounts;
  }
}</pre><pre class="programlisting">&lt;<span class="hl-tag">beans</span>&gt;
  &lt;<span class="hl-tag">bean</span> <span class="hl-attribute">id</span>=<span class="hl-value">"foo"</span> <span class="hl-attribute">class</span>=<span class="hl-value">"x.y.Foo"</span>&gt;
      &lt;<span class="hl-tag">property</span> <span class="hl-attribute">name</span>=<span class="hl-value">"accounts"</span>&gt;
          &lt;<span class="hl-tag">map</span>&gt;
              &lt;<span class="hl-tag">entry</span> <span class="hl-attribute">key</span>=<span class="hl-value">"one"</span> <span class="hl-attribute">value</span>=<span class="hl-value">"9.99"</span>/&gt;
              &lt;<span class="hl-tag">entry</span> <span class="hl-attribute">key</span>=<span class="hl-value">"two"</span> <span class="hl-attribute">value</span>=<span class="hl-value">"2.75"</span>/&gt;
              &lt;<span class="hl-tag">entry</span> <span class="hl-attribute">key</span>=<span class="hl-value">"six"</span> <span class="hl-attribute">value</span>=<span class="hl-value">"3.99"</span>/&gt;
          &lt;<span class="hl-tag">/map</span>&gt;
      &lt;<span class="hl-tag">/property</span>&gt;
  &lt;<span class="hl-tag">/bean</span>&gt;
&lt;<span class="hl-tag">/beans</span>&gt;</pre><p>When the <code class="literal">accounts</code> property of the
          <code class="literal">foo</code> bean is prepared for injection, the generics
          information about the element type of the strongly-typed
          <code class="classname">Map&lt;String, Float&gt;</code> is available by
          reflection. Thus Spring's type conversion infrastructure recognizes
          the various value elements as being of type
          <code class="classname">Float</code>, and the string values <code class="literal">9.99,
          2.75</code>, and <code class="literal">3.99</code> are converted into an
          actual <code class="classname">Float</code> type.</p></div></div><div class="section" lang="en"><div class="titlepage"><div><div><h4 class="title"><a name="beans-null-element"></a>4.4.2.5&nbsp;Null and empty string values</h4></div></div></div><p>Spring
        treats empty arguments for properties and the like as empty
        <code class="literal">Strings</code>. The following XML-based configuration
        metadata snippet sets the email property to the empty
        <code class="classname">String</code> value ("")</p><pre class="programlisting">&lt;<span class="hl-tag">bean</span> <span class="hl-attribute">class</span>=<span class="hl-value">"ExampleBean"</span>&gt;
&lt;<span class="hl-tag">property</span> <span class="hl-attribute">name</span>=<span class="hl-value">"email"</span> <span class="hl-attribute">value</span>=<span class="hl-value">""</span>/&gt;
&lt;<span class="hl-tag">/bean</span>&gt;</pre><p>The preceding example is equivalent to the following Java code:
        <code class="methodname">exampleBean.setEmail("")</code>. The
        <code class="literal">&lt;null/&gt;</code> element handles <code class="literal">null</code>
        values. For example:</p><pre class="programlisting">&lt;<span class="hl-tag">bean</span> <span class="hl-attribute">class</span>=<span class="hl-value">"ExampleBean"</span>&gt;
&lt;<span class="hl-tag">property</span> <span class="hl-attribute">name</span>=<span class="hl-value">"email"</span>&gt;&lt;<span class="hl-tag">null</span>/&gt;&lt;<span class="hl-tag">/property</span>&gt;
&lt;<span class="hl-tag">/bean</span>&gt;</pre><p>The above configuration is equivalent to the following Java code:
        <code class="methodname">exampleBean.setEmail(null)</code>.</p></div><div class="section" lang="en"><div class="titlepage"><div><div><h4 class="title"><a name="beans-p-namespace"></a>4.4.2.6&nbsp;XML shortcut with the p-namespace</h4></div></div></div><p>The p-namespace enables you to use the <code class="literal">bean</code>
        element's attributes, instead of nested
        <code class="literal">&lt;property/&gt;</code> elements, to describe your property
        values and/or collaborating beans.</p><p>Spring 2.0 and later supports extensible configuration formats <a class="link" href="xsd-config.html" title="Appendix&nbsp;C.&nbsp;XML Schema-based configuration">with namespaces</a>, which are based on an XML
        Schema definition. The <code class="literal">beans</code> configuration format
        discussed in this chapter is defined in an XML Schema document. However,
        the p-namespace is not defined in an XSD file and exists only in the
        core of Spring.</p><p>The following example shows two XML snippets that resolve to the
        same result: The first uses standard XML format and the second uses the
        p-namespace.</p><pre class="programlisting">&lt;<span class="hl-tag">beans</span> <span class="hl-attribute">xmlns</span>=<span class="hl-value">"http://www.springframework.org/schema/beans"</span>
  <span class="hl-attribute">xmlns:xsi</span>=<span class="hl-value">"http://www.w3.org/2001/XMLSchema-instance"</span>
  <span class="hl-attribute">xmlns:p</span>=<span class="hl-value">"http://www.springframework.org/schema/p"</span>
  <span class="hl-attribute">xsi:schemaLocation</span>=<span class="hl-value">"http://www.springframework.org/schema/beans
      http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"</span>&gt;

  &lt;<span class="hl-tag">bean</span> <span class="hl-attribute">name</span>=<span class="hl-value">"classic"</span> <span class="hl-attribute">class</span>=<span class="hl-value">"com.example.ExampleBean"</span>&gt;
      &lt;<span class="hl-tag">property</span> <span class="hl-attribute">name</span>=<span class="hl-value">"email"</span> <span class="hl-attribute">value</span>=<span class="hl-value">"foo@bar.com"</span>/&gt;
  &lt;<span class="hl-tag">/bean</span>&gt;

  &lt;<span class="hl-tag">bean</span> <span class="hl-attribute">name</span>=<span class="hl-value">"p-namespace"</span> <span class="hl-attribute">class</span>=<span class="hl-value">"com.example.ExampleBean"</span>
        <span class="hl-attribute">p:email</span>=<span class="hl-value">"foo@bar.com"</span>/&gt;
&lt;<span class="hl-tag">/beans</span>&gt;</pre><p>The example shows an attribute in the p-namespace called email in
        the bean definition. This tells Spring to include a property
        declaration. As previously mentioned, the p-namespace does not have a
        schema definition, so you can set the name of the attribute to the
        property name.</p><p>This next example includes two more bean definitions that both have
        a reference to another bean:</p><pre class="programlisting">&lt;<span class="hl-tag">beans</span> <span class="hl-attribute">xmlns</span>=<span class="hl-value">"http://www.springframework.org/schema/beans"</span>
  <span class="hl-attribute">xmlns:xsi</span>=<span class="hl-value">"http://www.w3.org/2001/XMLSchema-instance"</span>
  <span class="hl-attribute">xmlns:p</span>=<span class="hl-value">"http://www.springframework.org/schema/p"</span>
  <span class="hl-attribute">xsi:schemaLocation</span>=<span class="hl-value">"http://www.springframework.org/schema/beans
      http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"</span>&gt;

  &lt;<span class="hl-tag">bean</span> <span class="hl-attribute">name</span>=<span class="hl-value">"john-classic"</span> <span class="hl-attribute">class</span>=<span class="hl-value">"com.example.Person"</span>&gt;
      &lt;<span class="hl-tag">property</span> <span class="hl-attribute">name</span>=<span class="hl-value">"name"</span> <span class="hl-attribute">value</span>=<span class="hl-value">"John Doe"</span>/&gt;
      &lt;<span class="hl-tag">property</span> <span class="hl-attribute">name</span>=<span class="hl-value">"spouse"</span> <span class="hl-attribute">ref</span>=<span class="hl-value">"jane"</span>/&gt;
  &lt;<span class="hl-tag">/bean</span>&gt;

  &lt;<span class="hl-tag">bean</span> <span class="hl-attribute">name</span>=<span class="hl-value">"john-modern"</span>
      <span class="hl-attribute">class</span>=<span class="hl-value">"com.example.Person"</span>
      <span class="hl-attribute">p:name</span>=<span class="hl-value">"John Doe"</span>
      <span class="hl-attribute">p:spouse-ref</span>=<span class="hl-value">"jane"</span>/&gt;

  &lt;<span class="hl-tag">bean</span> <span class="hl-attribute">name</span>=<span class="hl-value">"jane"</span> <span class="hl-attribute">class</span>=<span class="hl-value">"com.example.Person"</span>&gt;
      &lt;<span class="hl-tag">property</span> <span class="hl-attribute">name</span>=<span class="hl-value">"name"</span> <span class="hl-attribute">value</span>=<span class="hl-value">"Jane Doe"</span>/&gt;
  &lt;<span class="hl-tag">/bean</span>&gt;
&lt;<span class="hl-tag">/beans</span>&gt;</pre><p>As you can see, this example includes not only a property value
        using the p-namespace, but also uses a special format to declare
        property references. Whereas the first bean definition uses
        <code class="literal">&lt;property name="spouse" ref="jane"/&gt;</code> to create
        a reference from bean <code class="literal">john</code> to bean
        <code class="literal">jane</code>, the second bean definition uses
        <code class="literal">p:spouse-ref="jane"</code> as an attribute to do the exact
        same thing. In this case <code class="literal">spouse</code> is the property name,
        whereas the <code class="literal">-ref</code> part indicates that this is not a
        straight value but rather a reference to another bean.</p><div class="note" style="margin-left: 0.5in; margin-right: 0.5in;"><table border="0" summary="Note"><tr><td rowspan="2" align="center" valign="top" width="25"><img alt="[Note]" src="images/note.gif"></td><th align="left">Note</th></tr><tr><td align="left" valign="top"><p>The p-namespace is not as flexible as the standard XML format. For
          example, the format for declaring property references clashes with
          properties that end in <code class="literal">Ref</code>, whereas the standard
          XML format does not. We recommend that you choose your approach
          carefully and communicate this to your team members, to avoid
          producing XML documents that use all three approaches at the same
          time.</p></td></tr></table></div></div><div class="section" lang="en"><div class="titlepage"><div><div><h4 class="title"><a name="beans-c-namespace"></a>4.4.2.7&nbsp;XML shortcut with the c-namespace</h4></div></div></div><p>Similar to the <a class="xref" href="beans.html#beans-p-namespace" title="4.4.2.6&nbsp;XML shortcut with the p-namespace">Section&nbsp;4.4.2.6, &#8220;XML shortcut with the p-namespace&#8221;</a>, the <span class="emphasis"><em>c-namespace</em></span>, newly introduced in Spring 3.1, 
      allows usage of inlined attributes for configuring the constructor arguments rather then nested <code class="literal">constructor-arg</code>
      elements.</p><p>Let's review the examples from <a class="xref" href="beans.html#beans-constructor-injection" title="4.4.1.1&nbsp;Constructor-based dependency injection">Section&nbsp;4.4.1.1, &#8220;Constructor-based dependency injection&#8221;</a> with the <code class="literal">c</code> namespace:</p><pre class="programlisting">&lt;beans xmlns=<span class="hl-string">"http://www.springframework.org/schema/beans"</span>
  xmlns:xsi=<span class="hl-string">"http://www.w3.org/2001/XMLSchema-instance"</span>
  xmlns:p=<span class="hl-string">"http://www.springframework.org/schema/c"</span>
  xsi:schemaLocation=<span class="hl-string">"http://www.springframework.org/schema/beans
      http://www.springframework.org/schema/beans/spring-beans.xsd"</span>&gt;
      
  &lt;bean id=<span class="hl-string">"bar"</span> <span class="hl-keyword">class</span>=<span class="hl-string">"x.y.Bar"</span>/&gt;
  &lt;bean id=<span class="hl-string">"baz"</span> <span class="hl-keyword">class</span>=<span class="hl-string">"x.y.Baz"</span>/&gt;

  &lt;-- <span class="hl-string">'traditional'</span> declaration --&gt;      
  &lt;bean id=<span class="hl-string">"foo"</span> <span class="hl-keyword">class</span>=<span class="hl-string">"x.y.Foo"</span>&gt;
      &lt;constructor-arg ref=<span class="hl-string">"bar"</span>/&gt;
      &lt;constructor-arg ref=<span class="hl-string">"baz"</span>/&gt;
      &lt;constructor-arg value=<span class="hl-string">"foo@bar.com"</span>/&gt;
  &lt;/bean&gt;

  &lt;-- <span class="hl-string">'c-namespace'</span> declaration --&gt;
  &lt;bean id=<span class="hl-string">"foo"</span> <span class="hl-keyword">class</span>=<span class="hl-string">"x.y.Foo"</span> c:bar-ref=<span class="hl-string">"bar"</span> c:baz-ref=<span class="hl-string">"baz"</span> c:email=<span class="hl-string">"foo@bar.com"</span>&gt;

&lt;/beans&gt;</pre><p>The <code class="literal">c:</code> namespace uses the same conventions as the <code class="literal">p:</code> one (trailing <code class="literal">-ref</code> for bean references)
	  for setting the constructor arguments by their names. And just as well, it needs to be declared even though it is not defined in an XSD schema
	  (but it exists inside the Spring core).</p><p>For the rare cases where the constructor argument names are not available (usually if the bytecode was compiled without debugging information), one can
	  use fallback to the argument indexes:</p><pre class="programlisting">&lt;-- <span class="hl-string">'c-namespace'</span> index declaration --&gt;
&lt;bean id=<span class="hl-string">"foo"</span> <span class="hl-keyword">class</span>=<span class="hl-string">"x.y.Foo"</span> c:_0-ref=<span class="hl-string">"bar"</span> c:_1-ref=<span class="hl-string">"baz"</span>&gt;</pre><div class="note" style="margin-left: 0.5in; margin-right: 0.5in;"><table border="0" summary="Note"><tr><td rowspan="2" align="center" valign="top" width="25"><img alt="[Note]" src="images/note.gif"></td><th align="left">Note</th></tr><tr><td align="left" valign="top">Due to the XML grammar, the index notation requires the presence of the leading <span class="emphasis"><em>_</em></span> as XML attribute names cannot start
      with a number (even though some IDE allow it).</td></tr></table></div><p>In practice, the constructor resolution <a class="link" href="beans.html#beans-factory-ctor-arguments-resolution" title="Constructor argument resolution">mechanism</a> is quite efficient in matching arguments so 
	  unless one really needs to, we recommend using the name notation through-out your configuration.</p></div><div class="section" lang="en"><div class="titlepage"><div><div><h4 class="title"><a name="beans-compound-property-names"></a>4.4.2.8&nbsp;Compound property names</h4></div></div></div><p>You can use compound or nested property names when you set bean
        properties, as long as all components of the path except the final
        property name are not <code class="literal">null</code>. Consider the following
        bean definition.</p><pre class="programlisting">&lt;<span class="hl-tag">bean</span> <span class="hl-attribute">id</span>=<span class="hl-value">"foo"</span> <span class="hl-attribute">class</span>=<span class="hl-value">"foo.Bar"</span>&gt;
&lt;<span class="hl-tag">property</span> <span class="hl-attribute">name</span>=<span class="hl-value">"fred.bob.sammy"</span> <span class="hl-attribute">value</span>=<span class="hl-value">"123"</span> /&gt;
&lt;<span class="hl-tag">/bean</span>&gt;</pre><p>The <code class="literal">foo</code> bean has a <code class="literal">fred</code>
        property, which has a <code class="literal">bob</code> property, which has a
        <code class="literal">sammy</code> property, and that final
        <code class="literal">sammy</code> property is being set to the value
        <code class="literal">123</code>. In order for this to work, the
        <code class="literal">fred</code> property of <code class="literal">foo</code>, and the
        <code class="literal">bob</code> property of <code class="literal">fred</code> must not be
        <code class="literal">null</code> after the bean is constructed, or a
        <code class="exceptionname">NullPointerException</code> is thrown.</p></div></div><div class="section" lang="en"><div class="titlepage"><div><div><h3 class="title"><a name="beans-factory-dependson"></a>4.4.3&nbsp;Using <code class="literal">depends-on</code></h3></div></div></div><p>If a bean is a dependency of another that usually means that one bean
      is set as a property of another. Typically you accomplish this with the
      <a class="link" href="beans.html#beans-ref-element" title="4.4.2.2&nbsp;References to other beans (collaborators)"><code class="literal">&lt;ref/&gt;</code>
      element</a> in XML-based configuration metadata. However, sometimes
      dependencies between beans are less direct; for example, a static
      initializer in a class needs to be triggered, such as database driver
      registration. The <code class="literal">depends-on</code> attribute can explicitly
      force one or more beans to be initialized before the bean using this
      element is initialized. The following example uses the
      <code class="literal">depends-on</code> attribute to express a dependency on a
      single bean:</p><pre class="programlisting">&lt;<span class="hl-tag">bean</span> <span class="hl-attribute">id</span>=<span class="hl-value">"beanOne"</span> <span class="hl-attribute">class</span>=<span class="hl-value">"ExampleBean"</span> <span class="hl-attribute">depends-on</span>=<span class="hl-value">"manager"</span>/&gt;

&lt;<span class="hl-tag">bean</span> <span class="hl-attribute">id</span>=<span class="hl-value">"manager"</span> <span class="hl-attribute">class</span>=<span class="hl-value">"ManagerBean"</span> /&gt;</pre><p>To express a dependency on multiple beans, supply a list of bean names
      as the value of the <code class="literal">depends-on</code> attribute, with commas,
      whitespace and semicolons, used as valid delimiters:</p><pre class="programlisting">&lt;<span class="hl-tag">bean</span> <span class="hl-attribute">id</span>=<span class="hl-value">"beanOne"</span> <span class="hl-attribute">class</span>=<span class="hl-value">"ExampleBean"</span> <span class="hl-attribute">depends-on</span>=<span class="hl-value">"manager,accountDao"</span>&gt;
&lt;<span class="hl-tag">property</span> <span class="hl-attribute">name</span>=<span class="hl-value">"manager"</span> <span class="hl-attribute">ref</span>=<span class="hl-value">"manager"</span> /&gt;
&lt;<span class="hl-tag">/bean</span>&gt;

&lt;<span class="hl-tag">bean</span> <span class="hl-attribute">id</span>=<span class="hl-value">"manager"</span> <span class="hl-attribute">class</span>=<span class="hl-value">"ManagerBean"</span> /&gt;
&lt;<span class="hl-tag">bean</span> <span class="hl-attribute">id</span>=<span class="hl-value">"accountDao"</span> <span class="hl-attribute">class</span>=<span class="hl-value">"x.y.jdbc.JdbcAccountDao"</span> /&gt;</pre><div class="note" style="margin-left: 0.5in; margin-right: 0.5in;"><table border="0" summary="Note"><tr><td rowspan="2" align="center" valign="top" width="25"><img alt="[Note]" src="images/note.gif"></td><th align="left">Note</th></tr><tr><td align="left" valign="top"><p>The <code class="literal">depends-on</code> attribute in the bean definition
        can specify both an initialization time dependency and, in the case of
        <a class="link" href="beans.html#beans-factory-scopes-singleton" title="4.5.1&nbsp;The singleton scope">singleton</a> beans
        only, a corresponding destroy time dependency. Dependent beans that
        define a <code class="literal">depends-on</code> relationship with a given bean
        are destroyed first, prior to the given bean itself being destroyed.
        Thus <code class="literal">depends-on</code> can also control shutdown
        order.</p></td></tr></table></div></div><div class="section" lang="en"><div class="titlepage"><div><div><h3 class="title"><a name="beans-factory-lazy-init"></a>4.4.4&nbsp;Lazy-initialized
      beans</h3></div></div></div><p>By default,<code class="interfacename"> ApplicationContext</code>
      implementations eagerly create and configure all <a class="link" href="beans.html#beans-factory-scopes-singleton" title="4.5.1&nbsp;The singleton scope">singleton</a> beans as part of
      the initialization process. Generally, this pre-instantiation is
      desirable, because errors in the configuration or surrounding environment
      are discovered immediately, as opposed to hours or even days later. When
      this behavior is <span class="emphasis"><em>not</em></span> desirable, you can prevent
      pre-instantiation of a singleton bean by marking the bean definition as
      lazy-initialized. A lazy-initialized bean tells the IoC container to
      create a bean instance when it is first requested, rather than at
      startup.</p><p>In XML, this behavior is controlled by the
      <code class="literal">lazy-init</code> attribute on the
      <code class="literal">&lt;bean/&gt;</code> element; for example:</p><pre class="programlisting">&lt;<span class="hl-tag">bean</span> <span class="hl-attribute">id</span>=<span class="hl-value">"lazy"</span> <span class="hl-attribute">class</span>=<span class="hl-value">"com.foo.ExpensiveToCreateBean"</span> <span class="hl-attribute">lazy-init</span>=<span class="hl-value">"true"</span>/&gt;

&lt;<span class="hl-tag">bean</span> <span class="hl-attribute">name</span>=<span class="hl-value">"not.lazy"</span> <span class="hl-attribute">class</span>=<span class="hl-value">"com.foo.AnotherBean"</span>/&gt;</pre><p>When the preceding configuration is consumed by an
      <code class="interfacename">ApplicationContext</code>, the bean named
      <code class="literal">lazy</code> is not eagerly pre-instantiated when the
      <code class="interfacename">ApplicationContext</code> is starting up, whereas
      the <code class="literal">not.lazy</code> bean is eagerly pre-instantiated.</p><p>However, when a lazy-initialized bean is a dependency of a singleton
      bean that is <span class="emphasis"><em>not</em></span> lazy-initialized, the
      <code class="interfacename">ApplicationContext</code> creates the
      lazy-initialized bean at startup, because it must satisfy the singleton's
      dependencies. The lazy-initialized bean is injected into a singleton bean
      elsewhere that is not lazy-initialized.</p><p>You can also control lazy-initialization at the container level by
      using the <code class="literal">default-lazy-init</code> attribute on the
      <code class="literal">&lt;beans/&gt;</code> element; for example:</p><pre class="programlisting">&lt;<span class="hl-tag">beans</span> <span class="hl-attribute">default-lazy-init</span>=<span class="hl-value">"true"</span>&gt;
  &lt;<span class="hl-comment">!-- no beans will be pre-instantiated... --</span>&gt;
&lt;<span class="hl-tag">/beans</span>&gt;</pre></div><div class="section" lang="en"><div class="titlepage"><div><div><h3 class="title"><a name="beans-factory-autowire"></a>4.4.5&nbsp;Autowiring collaborators</h3></div></div></div><p>The Spring container can <span class="emphasis"><em>autowire</em></span> relationships
      between collaborating beans. You can allow Spring to resolve collaborators
      (other beans) automatically for your bean by inspecting the contents of
      the <code class="interfacename">ApplicationContext</code>. Autowiring has the
      following advantages:</p><div class="itemizedlist"><ul type="disc"><li><p>Autowiring can significantly reduce the need to specify properties
          or constructor arguments. (Other mechanisms such as a bean template
          <a class="link" href="beans.html#beans-child-bean-definitions" title="4.7&nbsp;Bean definition inheritance">discussed elsewhere in
          this chapter</a> are also valuable in this regard.)</p></li><li><p>Autowiring can update a configuration as your objects evolve. For
          example, if you need to add a dependency to a class, that dependency
          can be satisfied automatically without you needing to modify the
          configuration. Thus autowiring can be especially useful during
          development, without negating the option of switching to explicit
          wiring when the code base becomes more stable.</p></li></ul></div><p> When using XML-based configuration metadata<sup>[<a name="d0e3664" href="#ftn.d0e3664" class="footnote">2</a>]</sup>, you specify autowire mode for a bean definition with the
      <code class="literal">autowire</code> attribute of the
      <code class="literal">&lt;bean/&gt;</code> element. The autowiring functionality has
      five modes. You specify autowiring <span class="emphasis"><em>per</em></span> bean and thus
      can choose which ones to autowire.</p><div class="table"><a name="beans-factory-autowiring-modes-tbl"></a><p class="title"><b>Table&nbsp;4.2.&nbsp;Autowiring modes</b></p><div class="table-contents"><table summary="Autowiring modes" style="border-collapse: collapse;border-top: 1.0pt solid ; border-bottom: 1.0pt solid ; border-left: 1.0pt solid ; border-right: 1.0pt solid ; "><colgroup><col><col></colgroup><thead><tr><th style="border-right: 1.0pt solid ; border-bottom: 1.0pt solid ; ">Mode</th><th style="border-bottom: 1.0pt solid ; ">Explanation</th></tr></thead><tbody><tr><td style="border-right: 1.0pt solid ; border-bottom: 1.0pt solid ; ">no</td><td style="border-bottom: 1.0pt solid ; "><p>(Default) No autowiring. Bean references must be
              defined via a <code class="literal">ref</code> element. Changing the default
              setting is not recommended for larger deployments, because
              specifying collaborators explicitly gives greater control and
              clarity. To some extent, it documents the structure of a
              system.</p></td></tr><tr><td style="border-right: 1.0pt solid ; border-bottom: 1.0pt solid ; ">byName</td><td style="border-bottom: 1.0pt solid ; "><p>Autowiring by property name. Spring looks for a bean
              with the same name as the property that needs to be autowired. For
              example, if a bean definition is set to autowire by name, and it
              contains a <span class="emphasis"><em>master</em></span> property (that is, it has a
              <span class="emphasis"><em>setMaster(..)</em></span> method), Spring looks for a
              bean definition named <code class="literal">master</code>, and uses it to
              set the property.</p></td></tr><tr><td style="border-right: 1.0pt solid ; border-bottom: 1.0pt solid ; ">byType</td><td style="border-bottom: 1.0pt solid ; "><p>Allows a property to be autowired if exactly one bean
              of the property type exists in the container. If more than one
              exists, a fatal exception is thrown, which indicates that you may
              not use <span class="emphasis"><em>byType</em></span> autowiring for that bean. If
              there are no matching beans, nothing happens; the property is not
              set.</p></td></tr><tr><td style="border-right: 1.0pt solid ; ">constructor</td><td style=""><p>Analogous to <span class="emphasis"><em>byType</em></span>, but applies
              to constructor arguments. If there is not exactly one bean of the
              constructor argument type in the container, a fatal error is
              raised.</p></td></tr></tbody></table></div></div><br class="table-break"><p>With <span class="emphasis"><em>byType</em></span> or <span class="emphasis"><em>constructor</em></span>
      autowiring mode, you can wire arrays and typed-collections. In such cases
      <span class="emphasis"><em>all</em></span> autowire candidates within the container that
      match the expected type are provided to satisfy the dependency. You can
      autowire strongly-typed Maps if the expected key type is
      <code class="classname">String</code>. An autowired Maps values will consist of
      all bean instances that match the expected type, and the Maps keys will
      contain the corresponding bean names.</p><p>You can combine autowire behavior with dependency checking, which is
      performed after autowiring completes.</p><div class="section" lang="en"><div class="titlepage"><div><div><h4 class="title"><a name="beans-autowired-exceptions"></a>4.4.5.1&nbsp;Limitations and disadvantages of autowiring</h4></div></div></div><p>Autowiring works best when it is used consistently across a project.
        If autowiring is not used in general, it might be confusing to
        developers to use it to wire only one or two bean definitions.</p><p>Consider the limitations and disadvantages of autowiring:</p><div class="itemizedlist"><ul type="disc"><li><p>Explicit dependencies in <code class="literal">property</code> and
            <code class="literal">constructor-arg</code> settings always override
            autowiring. You cannot autowire so-called
            <span class="emphasis"><em>simple</em></span> properties such as primitives,
            <code class="classname">Strings</code>, and <code class="classname">Classes</code>
            (and arrays of such simple properties). This limitation is
            by-design.</p></li></ul></div><div class="itemizedlist"><ul type="disc"><li><p>Autowiring is less exact than explicit wiring. Although, as
            noted in the above table, Spring is careful to avoid guessing in
            case of ambiguity that might have unexpected results, the
            relationships between your Spring-managed objects are no longer
            documented explicitly.</p></li><li><p>Wiring information may not be available to tools that may
            generate documentation from a Spring container.</p></li></ul></div><div class="itemizedlist"><ul type="disc"><li><p>Multiple bean definitions within the container may match the
            type specified by the setter method or constructor argument to be
            autowired. For arrays, collections, or Maps, this is not necessarily
            a problem. However for dependencies that expect a single value, this
            ambiguity is not arbitrarily resolved. If no unique bean definition
            is available, an exception is thrown.</p></li></ul></div><p>In the latter scenario, you have several options:</p><div class="itemizedlist"><ul type="disc"><li><p>Abandon autowiring in favor of explicit wiring.</p></li><li><p>Avoid autowiring for a bean definition by setting its
            <code class="literal">autowire-candidate</code> attributes to
            <code class="literal">false</code> as described in the next section.</p></li><li><p>Designate a single bean definition as the
            <span class="emphasis"><em>primary</em></span> candidate by setting the
            <code class="literal">primary</code> attribute of its
            <code class="literal">&lt;bean/&gt;</code> element to
            <code class="literal">true</code>.</p></li><li><p>If you are using Java 5 or later, implement the more
            fine-grained control available with annotation-based configuration,
            as described in <a class="xref" href="beans.html#beans-annotation-config" title="4.9&nbsp;Annotation-based container configuration">Section&nbsp;4.9, &#8220;Annotation-based container configuration&#8221;</a>.</p></li></ul></div></div><div class="section" lang="en"><div class="titlepage"><div><div><h4 class="title"><a name="beans-factory-autowire-candidate"></a>4.4.5.2&nbsp;Excluding a bean from autowiring</h4></div></div></div><p>On a per-bean basis, you can exclude a bean from autowiring. In
        Spring's XML format, set the <code class="literal">autowire-candidate</code>
        attribute of the <code class="literal">&lt;bean/&gt;</code> element to
        <code class="literal">false</code>; the container makes that specific bean
        definition unavailable to the autowiring infrastructure (including
        annotation style configurations such as <a class="link" href="beans.html#beans-autowired-annotation" title="4.9.2&nbsp;@Autowired and @Inject"><code class="interfacename">@Autowired</code></a>).</p><p>You can also limit autowire candidates based on pattern-matching
        against bean names. The top-level <code class="literal">&lt;beans/&gt;</code>
        element accepts one or more patterns within its
        <code class="literal">default-autowire-candidates</code> attribute. For example,
        to limit autowire candidate status to any bean whose name ends with
        <span class="emphasis"><em>Repository,</em></span> provide a value of *Repository. To
        provide multiple patterns, define them in a comma-separated list. An
        explicit value of <code class="literal">true</code> or <code class="literal">false</code>
        for a bean definitions <code class="literal">autowire-candidate</code> attribute
        always takes precedence, and for such beans, the pattern matching rules
        do not apply.</p><p>These techniques are useful for beans that you never want to be
        injected into other beans by autowiring. It does not mean that an
        excluded bean cannot itself be configured using autowiring. Rather, the
        bean itself is not a candidate for autowiring other beans.</p></div></div><div class="section" lang="en"><div class="titlepage"><div><div><h3 class="title"><a name="beans-factory-method-injection"></a>4.4.6&nbsp;Method injection</h3></div></div></div><p>In most application scenarios, most beans in the container are <a class="link" href="beans.html#beans-factory-scopes-singleton" title="4.5.1&nbsp;The singleton scope">singletons</a>. When a
      singleton bean needs to collaborate with another singleton bean, or a
      non-singleton bean needs to collaborate with another non-singleton bean,
      you typically handle the dependency by defining one bean as a property of
      the other. A problem arises when the bean lifecycles are different.
      Suppose singleton bean A needs to use non-singleton (prototype) bean B,
      perhaps on each method invocation on A. The container only creates the
      singleton bean A once, and thus only gets one opportunity to set the
      properties. The container cannot provide bean A with a new instance of
      bean B every time one is needed.</p><p>A solution is to forego some inversion of control. You can <a class="link" href="beans.html#beans-factory-aware" title="4.6.2&nbsp;ApplicationContextAware and BeanNameAware">make bean A aware of the container</a> by
      implementing the <code class="interfacename">ApplicationContextAware</code>
      interface, and by <a class="link" href="beans.html#beans-factory-client" title="4.2.3&nbsp;Using the container">making a
      getBean("B") call to the container</a> ask for (a typically new) bean B
      instance every time bean A needs it. The following is an example of this
      approach:</p><pre class="programlisting"><span class="hl-comment">// a class that uses a stateful Command-style class to perform some processing</span>
<span class="hl-keyword">package</span> fiona.apple;

<span class="hl-comment">// Spring-API imports</span>
<span class="hl-keyword">import</span> org.springframework.beans.BeansException;
<span class="hl-keyword">import</span> org.springframework.context.Applicationcontext;
<span class="hl-keyword">import</span> org.springframework.context.ApplicationContextAware;

<span class="hl-keyword">public</span> <span class="hl-keyword">class</span> CommandManager <span class="hl-keyword">implements</span> ApplicationContextAware {

 <span class="hl-keyword">private</span> ApplicationContext applicationContext;

 <span class="hl-keyword">public</span> Object process(Map commandState) {
    <span class="hl-comment">// grab a new instance of the appropriate Command</span>
    Command command = createCommand();
    <span class="hl-comment">// set the state on the (hopefully brand new) Command instance</span>
    command.setState(commandState);
    <span class="hl-keyword">return</span> command.execute();
 }

 <span class="hl-keyword">protected</span> Command createCommand() {
    <span class="hl-comment">// notice the Spring API dependency!</span>
    <span class="hl-keyword">return</span> <span class="hl-keyword">this</span>.applicationContext.getBean(<span class="hl-string">"command"</span>, Command.<span class="hl-keyword">class</span>);
 }

 <span class="hl-keyword">public</span> <span class="hl-keyword">void</span> setApplicationContext(ApplicationContext applicationContext)
                                                                  <span class="hl-keyword">throws</span> BeansException {
    <span class="hl-keyword">this</span>.applicationContext = applicationContext;
 }
}</pre><p>The preceding is not desirable, because the business code is aware of
      and coupled to the Spring Framework. Method Injection, a somewhat advanced
      feature of the Spring IoC container, allows this use case to be handled in
      a clean
      fashion.</p><div class="sidebar"><p class="title"><b></b></p><p>You can read more about the motivation for Method Injection in
        <a class="ulink" href="http://blog.springsource.com/2004/08/06/method-injection/" target="_top">this blog entry</a>.</p></div><div class="section" lang="en"><div class="titlepage"><div><div><h4 class="title"><a name="beans-factory-lookup-method-injection"></a>4.4.6.1&nbsp;Lookup method injection</h4></div></div></div><p>Lookup method injection is the ability of the container to override
        methods on <span class="emphasis"><em>container managed beans</em></span>, to return the
        lookup result for another named bean in the container. The lookup
        typically involves a prototype bean as in the scenario described in the
        preceding section. The Spring Framework implements this method injection
        by using bytecode generation from the CGLIB library to generate
        dynamically a subclass that overrides the
        method.</p><div class="note" style="margin-left: 0.5in; margin-right: 0.5in;"><table border="0" summary="Note"><tr><td rowspan="2" align="center" valign="top" width="25"><img alt="[Note]" src="images/note.gif"></td><th align="left">Note</th></tr><tr><td align="left" valign="top"><p>For this dynamic subclassing to work, you must have the CGLIB
          jar(s) in your classpath. The class that the Spring container will
          subclass cannot be <code class="literal">final</code>, and the method to be
          overridden cannot be <code class="literal">final</code> either. Also, testing a
          class that has an <code class="literal">abstract</code> method requires you to
          subclass the class yourself and to supply a stub implementation of the
          <code class="literal">abstract</code> method. Finally, objects that have been
          the target of method injection cannot be serialized.</p></td></tr></table></div><p>Looking at the <code class="classname">CommandManager</code> class in the
        previous code snippet, you see that the Spring container will
        dynamically override the implementation of the
        <code class="methodname">createCommand()</code> method. Your
        <code class="classname">CommandManager</code> class will not have any Spring
        dependencies, as can be seen in the reworked example:</p><pre class="programlisting"><span class="hl-keyword">package</span> fiona.apple;

<span class="hl-comment">// no more Spring imports! </span>

<span class="hl-keyword">public</span> <span class="hl-keyword">abstract</span> <span class="hl-keyword">class</span> CommandManager {

 <span class="hl-keyword">public</span> Object process(Object commandState) {
    <span class="hl-comment">// grab a new instance of the appropriate Command interface</span>
    Command command = createCommand();
    <span class="hl-comment">// set the state on the (hopefully brand new) Command instance</span>
    command.setState(commandState);
    <span class="hl-keyword">return</span> command.execute();
 }

  <span class="hl-comment">// okay... but where is the implementation of this method?</span>
 <span class="hl-keyword">protected</span> <span class="hl-keyword">abstract</span> Command createCommand();
}</pre><p>In the client class containing the method to be injected (the
        <code class="classname">CommandManager</code> in this case), the method to be
        injected requires a signature of the following form:</p><pre class="programlisting">&lt;<span class="hl-tag">public|protected</span>&gt; [abstract] &lt;<span class="hl-tag">return-type</span>&gt; theMethodName(no-arguments);</pre><p>If the method is <code class="literal">abstract</code>, the
        dynamically-generated subclass implements the method. Otherwise, the
        dynamically-generated subclass overrides the concrete method defined in
        the original class. For example:</p><pre class="programlisting">&lt;<span class="hl-comment">!-- a stateful bean deployed as a prototype (non-singleton) --</span>&gt;
&lt;<span class="hl-tag">bean</span> <span class="hl-attribute">id</span>=<span class="hl-value">"command"</span> <span class="hl-attribute">class</span>=<span class="hl-value">"fiona.apple.AsyncCommand"</span> <span class="hl-attribute">scope</span>=<span class="hl-value">"prototype"</span>&gt;
&lt;<span class="hl-comment">!-- inject dependencies here as required --</span>&gt;
&lt;<span class="hl-tag">/bean</span>&gt;

&lt;<span class="hl-comment">!-- commandProcessor uses statefulCommandHelper --</span>&gt;
&lt;<span class="hl-tag">bean</span> <span class="hl-attribute">id</span>=<span class="hl-value">"commandManager"</span> <span class="hl-attribute">class</span>=<span class="hl-value">"fiona.apple.CommandManager"</span>&gt;
&lt;<span class="hl-tag">lookup-method</span> <span class="hl-attribute">name</span>=<span class="hl-value">"createCommand"</span> <span class="hl-attribute">bean</span>=<span class="hl-value">"command"</span>/&gt;
&lt;<span class="hl-tag">/bean</span>&gt;</pre><p>The bean identified as <span class="emphasis"><em>commandManager</em></span> calls its
        own method <code class="methodname">createCommand()</code> whenever it needs a
        new instance of the <span class="emphasis"><em>command</em></span> bean. You must be
        careful to deploy the <code class="literal">command</code> bean as a prototype, if
        that is actually what is needed. If it is deployed as a <a class="link" href="beans.html#beans-factory-scopes-singleton" title="4.5.1&nbsp;The singleton scope">singleton</a>, the same
        instance of the <code class="literal">command</code> bean is returned each
        time.</p><div class="tip" style="margin-left: 0.5in; margin-right: 0.5in;"><table border="0" summary="Tip"><tr><td rowspan="2" align="center" valign="top" width="25"><img alt="[Tip]" src="images/tip.gif"></td><th align="left">Tip</th></tr><tr><td align="left" valign="top"><p>The interested reader may also find the
          <code class="classname">ServiceLocatorFactoryBean</code> (in the
          <code class="literal">org.springframework.beans.factory.config</code> package)
          to be of use. The approach used in ServiceLocatorFactoryBean is
          similar to that of another utility class,
          <code class="classname">ObjectFactoryCreatingFactoryBean</code>, but it allows
          you to specify your own lookup interface as opposed to a
          Spring-specific lookup interface. Consult the JavaDocs for these
          classes as well as this <a class="ulink" href="http://blog.arendsen.net/index.php/2006/10/05/on-the-servicelocatorfactorybean-dlas-and-the-sustainability-of-code-and-design/" target="_top">blog entry</a> for additional information
          ServiceLocatorFactoryBean.</p></td></tr></table></div></div><div class="section" lang="en"><div class="titlepage"><div><div><h4 class="title"><a name="beans-factory-arbitrary-method-replacement"></a>4.4.6.2&nbsp;Arbitrary method replacement</h4></div></div></div><p>A less useful form of method injection than lookup method Injection
        is the ability to replace arbitrary methods in a managed bean with
        another method implementation. Users may safely skip the rest of this
        section until the functionality is actually
        needed.</p><p>With XML-based configuration metadata, you can use the
        <code class="literal">replaced-method</code> element to replace an existing method
        implementation with another, for a deployed bean. Consider the following
        class, with a method computeValue, which we want to override:</p><pre class="programlisting"><span class="hl-keyword">public</span> <span class="hl-keyword">class</span> MyValueCalculator {

<span class="hl-keyword">public</span> String computeValue(String input) {
  <span class="hl-comment">// some real code...</span>
}

<span class="hl-comment">// some other methods...</span>

}</pre><p>A class implementing the
        <code class="interfacename">org.springframework.beans.factory.support.MethodReplacer</code>
        interface provides the new method definition.</p><pre class="programlisting"><span class="hl-comment">/** meant to be used to override the existing computeValue(String)
  implementation in MyValueCalculator
*/</span>
<span class="hl-keyword">public</span> <span class="hl-keyword">class</span> ReplacementComputeValue <span class="hl-keyword">implements</span> MethodReplacer {

  <span class="hl-keyword">public</span> Object reimplement(Object o, Method m, Object[] args) <span class="hl-keyword">throws</span> Throwable {
      <span class="hl-comment">// get the input value, work with it, and return a computed result</span>
      String input = (String) args[0];
      ...
      <span class="hl-keyword">return</span> ...;
  }
}</pre><p>The bean definition to deploy the original class and specify the
        method override would look like this:</p><pre class="programlisting">&lt;<span class="hl-tag">bean</span> <span class="hl-attribute">id</span>=<span class="hl-value">"myValueCalculator"</span> <span class="hl-attribute">class</span>=<span class="hl-value">"x.y.z.MyValueCalculator"</span>&gt;

&lt;<span class="hl-comment">!-- arbitrary method replacement --</span>&gt;
&lt;<span class="hl-tag">replaced-method</span> <span class="hl-attribute">name</span>=<span class="hl-value">"computeValue"</span> <span class="hl-attribute">replacer</span>=<span class="hl-value">"replacementComputeValue"</span>&gt;
  &lt;<span class="hl-tag">arg-type</span>&gt;String&lt;<span class="hl-tag">/arg-type</span>&gt;
&lt;<span class="hl-tag">/replaced-method</span>&gt;
&lt;<span class="hl-tag">/bean</span>&gt;

&lt;<span class="hl-tag">bean</span> <span class="hl-attribute">id</span>=<span class="hl-value">"replacementComputeValue"</span> <span class="hl-attribute">class</span>=<span class="hl-value">"a.b.c.ReplacementComputeValue"</span>/&gt;</pre><p>You can use one or more contained
        <code class="literal">&lt;arg-type/&gt;</code> elements within the
        <code class="literal">&lt;replaced-method/&gt;</code> element to indicate the
        method signature of the method being overridden. The signature for the
        arguments is necessary only if the method is overloaded and multiple
        variants exist within the class. For convenience, the type string for an
        argument may be a substring of the fully qualified type name. For
        example, the following all match
        <code class="classname">java.lang.String</code>:</p><pre class="programlisting">    java.lang.String
  String
  Str</pre><p>Because the number of arguments is often enough to distinguish
        between each possible choice, this shortcut can save a lot of typing, by
        allowing you to type only the shortest string that will match an
        argument type.</p></div></div></div><div class="section" lang="en"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="beans-factory-scopes"></a>4.5&nbsp;Bean scopes</h2></div></div></div><p>When you create a bean definition, you create a
    <span class="emphasis"><em>recipe</em></span> for creating actual instances of the class
    defined by that bean definition. The idea that a bean definition is a recipe
    is important, because it means that, as with a class, you can create many
    object instances from a single recipe.</p><p>You can control not only the various dependencies and configuration
    values that are to be plugged into an object that is created from a
    particular bean definition, but also the <em class="firstterm">scope</em> of the
    objects created from a particular bean definition. This approach is powerful
    and flexible in that you can <span class="emphasis"><em>choose</em></span> the scope of the
    objects you create through configuration instead of having to bake in the
    scope of an object at the Java class level. Beans can be defined to be
    deployed in one of a number of scopes: out of the box, the Spring Framework
    supports five scopes, three of which are available only if you use a
    web-aware <code class="interfacename">ApplicationContext</code>.</p><p>The following scopes are supported out of the box. You can also create
    <a class="link" href="beans.html#beans-factory-scopes-custom" title="4.5.5&nbsp;Custom scopes">a custom scope.</a></p><div class="table"><a name="beans-factory-scopes-tbl"></a><p class="title"><b>Table&nbsp;4.3.&nbsp;Bean scopes</b></p><div class="table-contents"><table summary="Bean scopes" style="border-collapse: collapse;border-top: 1.0pt solid ; border-bottom: 1.0pt solid ; border-left: 1.0pt solid ; border-right: 1.0pt solid ; "><colgroup><col><col></colgroup><thead><tr><th style="border-right: 1.0pt solid ; border-bottom: 1.0pt solid ; " align="center">Scope</th><th style="border-bottom: 1.0pt solid ; " align="center">Description</th></tr></thead><tbody><tr><td style="border-right: 1.0pt solid ; border-bottom: 1.0pt solid ; "><p> <a class="link" href="beans.html#beans-factory-scopes-singleton" title="4.5.1&nbsp;The singleton scope">singleton</a> </p></td><td style="border-bottom: 1.0pt solid ; "><p>(Default) Scopes a single bean definition to a single
            object instance per Spring IoC container.</p></td></tr><tr><td style="border-right: 1.0pt solid ; border-bottom: 1.0pt solid ; "><p> <a class="link" href="beans.html#beans-factory-scopes-prototype" title="4.5.2&nbsp;The prototype scope">prototype</a> </p></td><td style="border-bottom: 1.0pt solid ; "><p>Scopes a single bean definition to any number of object
            instances.</p></td></tr><tr><td style="border-right: 1.0pt solid ; border-bottom: 1.0pt solid ; "><p> <a class="link" href="beans.html#beans-factory-scopes-request" title="4.5.4.2&nbsp;Request scope">request</a> </p></td><td style="border-bottom: 1.0pt solid ; "><p>Scopes a single bean definition to the lifecycle of a
            single HTTP request; that is, each HTTP request has its own instance
            of a bean created off the back of a single bean definition. Only
            valid in the context of a web-aware Spring
            <code class="interfacename">ApplicationContext</code>.</p></td></tr><tr><td style="border-right: 1.0pt solid ; border-bottom: 1.0pt solid ; "><p> <a class="link" href="beans.html#beans-factory-scopes-session" title="4.5.4.3&nbsp;Session scope">session</a> </p></td><td style="border-bottom: 1.0pt solid ; "><p>Scopes a single bean definition to the lifecycle of an
            HTTP <code class="interfacename">Session</code>. Only valid in the
            context of a web-aware Spring
            <code class="interfacename">ApplicationContext</code>.</p></td></tr><tr><td style="border-right: 1.0pt solid ; "><p> <a class="link" href="beans.html#beans-factory-scopes-global-session" title="4.5.4.4&nbsp;Global session scope">global session</a> </p></td><td style=""><p>Scopes a single bean definition to the lifecycle of a
            global HTTP <code class="interfacename">Session</code>. Typically only
            valid when used in a portlet context. Only valid in the context of a
            web-aware Spring
            <code class="interfacename">ApplicationContext</code>.</p></td></tr></tbody></table></div></div><br class="table-break"><div class="note" style="margin-left: 0.5in; margin-right: 0.5in;"><table border="0" summary="Note: Thread-scoped beans"><tr><td rowspan="2" align="center" valign="top" width="25"><img alt="[Note]" src="images/note.gif"></td><th align="left">Thread-scoped beans</th></tr><tr><td align="left" valign="top"><p>As of Spring 3.0, a <span class="emphasis"><em>thread scope</em></span> is available,
      but is not registered by default. For more information, see the
      documentation for <a class="ulink" href="http://static.springsource.org/spring/docs/3.0.x/javadoc-api/org/springframework/context/support/SimpleThreadScope.html" target="_top">SimpleThreadScope</a>. For instructions on how to register this or
      any other custom scope, see <a class="xref" href="beans.html#beans-factory-scopes-custom-using" title="4.5.5.2&nbsp;Using a custom scope">Section&nbsp;4.5.5.2, &#8220;Using a custom scope&#8221;</a>.</p></td></tr></table></div><div class="section" lang="en"><div class="titlepage"><div><div><h3 class="title"><a name="beans-factory-scopes-singleton"></a>4.5.1&nbsp;The singleton scope</h3></div></div></div><p>Only one <span class="emphasis"><em>shared</em></span> instance of a singleton bean is
      managed, and all requests for beans with an id or ids matching that bean
      definition result in that one specific bean instance being returned by the
      Spring container.</p><p>To put it another way, when you define a bean definition and it is
      scoped as a singleton, the Spring IoC container creates <span class="emphasis"><em>exactly
      one</em></span> instance of the object defined by that bean definition.
      This single instance is stored in a cache of such singleton beans, and
      <span class="emphasis"><em>all subsequent requests and references</em></span> for that named
      bean return the cached object.</p><div class="mediaobject" align="center"><img src="images/singleton.png" align="middle"></div><p>Spring's concept of a singleton bean differs from the Singleton
      pattern as defined in the Gang of Four (GoF) patterns book. The GoF
      Singleton hard-codes the scope of an object such that one <span class="emphasis"><em>and
      only one</em></span> instance of a particular class is created<span class="emphasis"><em>
      per <code class="classname">ClassLoader</code></em></span>. The scope of the Spring
      singleton is best described as <span class="emphasis"><em>per container and per
      bean</em></span>. This means that if you define one bean for a particular
      class in a single Spring container, then the Spring container creates one
      <span class="emphasis"><em>and only one</em></span> instance of the class defined by that
      bean definition. <span class="emphasis"><em>The singleton scope is the default scope in
      Spring</em></span>. To define a bean as a singleton in XML, you would
      write, for example:</p><pre class="programlisting">&lt;<span class="hl-tag">bean</span> <span class="hl-attribute">id</span>=<span class="hl-value">"accountService"</span> <span class="hl-attribute">class</span>=<span class="hl-value">"com.foo.DefaultAccountService"</span>/&gt;

&lt;<span class="hl-comment">!-- the following is equivalent, though redundant (singleton scope is the default) --</span>&gt;
&lt;<span class="hl-tag">bean</span> <span class="hl-attribute">id</span>=<span class="hl-value">"accountService"</span> <span class="hl-attribute">class</span>=<span class="hl-value">"com.foo.DefaultAccountService"</span> <span class="hl-attribute">scope</span>=<span class="hl-value">"singleton"</span>/&gt;</pre></div><div class="section" lang="en"><div class="titlepage"><div><div><h3 class="title"><a name="beans-factory-scopes-prototype"></a>4.5.2&nbsp;The prototype scope</h3></div></div></div><p>The non-singleton, prototype scope of bean deployment results in the
      <span class="emphasis"><em>creation of a new bean instance</em></span> every time a request
      for that specific bean is made. That is, the bean is injected into another
      bean or you request it through a <code class="literal">getBean()</code> method call
      on the container. As a rule, use the prototype scope for all stateful
      beans and the singleton scope for stateless beans.</p><p>The following diagram illustrates the Spring prototype scope.
      <span class="emphasis"><em>A data access object (DAO) is not typically configured as a
      prototype, because a typical DAO does not hold any conversational state;
      it was just easier for this author to reuse the core of the singleton
      diagram.</em></span></p><div class="mediaobject" align="center"><img src="images/prototype.png" align="middle"></div><p>The following example defines a bean as a prototype in XML:</p><pre class="programlisting">&lt;<span class="hl-comment">!-- using spring-beans-2.0.dtd --</span>&gt;
&lt;<span class="hl-tag">bean</span> <span class="hl-attribute">id</span>=<span class="hl-value">"accountService"</span> <span class="hl-attribute">class</span>=<span class="hl-value">"com.foo.DefaultAccountService"</span> <span class="hl-attribute">scope</span>=<span class="hl-value">"prototype"</span>/&gt;</pre><p>In contrast to the other scopes, Spring does not manage the complete
      lifecycle of a prototype bean: the container instantiates, configures, and
      otherwise assembles a prototype object, and hands it to the client, with
      no further record of that prototype instance. Thus, although
      <span class="emphasis"><em>initialization</em></span> lifecycle callback methods are called
      on all objects regardless of scope, in the case of prototypes, configured
      <span class="emphasis"><em>destruction</em></span> lifecycle callbacks are
      <span class="emphasis"><em>not</em></span> called. The client code must clean up
      prototype-scoped objects and release expensive resources that the
      prototype bean(s) are holding. To get the Spring container to release
      resources held by prototype-scoped beans, try using a custom <a class="link" href="beans.html#beans-factory-extension-bpp" title="4.8.1&nbsp;Customizing beans using a BeanPostProcessor">bean post-processor</a>, which
      holds a reference to beans that need to be cleaned up.</p><p>In some respects, the Spring container's role in regard to a
      prototype-scoped bean is a replacement for the Java <code class="literal">new</code>
      operator. All lifecycle management past that point must be handled by the
      client. (For details on the lifecycle of a bean in the Spring container,
      see <a class="xref" href="beans.html#beans-factory-lifecycle" title="4.6.1&nbsp;Lifecycle callbacks">Section&nbsp;4.6.1, &#8220;Lifecycle callbacks&#8221;</a>.)</p></div><div class="section" lang="en"><div class="titlepage"><div><div><h3 class="title"><a name="beans-factory-scopes-sing-prot-interaction"></a>4.5.3&nbsp;Singleton beans with prototype-bean dependencies</h3></div></div></div><p>When you use singleton-scoped beans with dependencies on prototype
      beans, be aware that <span class="emphasis"><em>dependencies are resolved at instantiation
      time</em></span>. Thus if you dependency-inject a prototype-scoped bean
      into a singleton-scoped bean, a new prototype bean is instantiated and
      then dependency-injected into the singleton bean. The prototype instance
      is the sole instance that is ever supplied to the singleton-scoped
      bean.</p><p>However, suppose you want the singleton-scoped bean to acquire a new
      instance of the prototype-scoped bean repeatedly at runtime. You cannot
      dependency-inject a prototype-scoped bean into your singleton bean,
      because that injection occurs only <span class="emphasis"><em>once</em></span>, when the
      Spring container is instantiating the singleton bean and resolving and
      injecting its dependencies. If you need a new instance of a prototype bean
      at runtime more than once, see <a class="xref" href="beans.html#beans-factory-method-injection" title="4.4.6&nbsp;Method injection">Section&nbsp;4.4.6, &#8220;Method injection&#8221;</a></p></div><div class="section" lang="en"><div class="titlepage"><div><div><h3 class="title"><a name="beans-factory-scopes-other"></a>4.5.4&nbsp;Request, session, and global session scopes</h3></div></div></div><p>The <code class="literal">request</code>, <code class="literal">session</code>, and
      <code class="literal">global session</code> scopes are <span class="emphasis"><em>only</em></span>
      available if you use a web-aware Spring
      <code class="interfacename">ApplicationContext</code> implementation (such as
      <code class="classname">XmlWebApplicationContext</code>). If you use these scopes
      with regular Spring IoC containers such as the
      <code class="classname">ClassPathXmlApplicationContext</code>, you get an
      <code class="classname">IllegalStateException</code> complaining about an unknown
      bean scope.</p><div class="section" lang="en"><div class="titlepage"><div><div><h4 class="title"><a name="beans-factory-scopes-other-web-configuration"></a>4.5.4.1&nbsp;Initial web configuration</h4></div></div></div><p>To support the scoping of beans at the <code class="literal">request</code>,
        <code class="literal">session</code>, and <code class="literal">global session</code> levels
        (web-scoped beans), some minor initial configuration is required before
        you define your beans. (This initial setup is <span class="emphasis"><em>not</em></span>
        required for the standard scopes, singleton and prototype.)</p><p>How you accomplish this initial setup depends on your particular
        Servlet environment..</p><p>If you access scoped beans within Spring Web MVC, in effect, within
        a request that is processed by the Spring
        <code class="classname">DispatcherServlet</code>, or
        <code class="classname">DispatcherPortlet</code>, then no special setup is
        necessary: <code class="classname">DispatcherServlet</code> and
        <code class="classname">DispatcherPortlet</code> already expose all relevant
        state.</p><p>If you use a Servlet 2.4+ web container, with requests processed
        outside of Spring's DispatcherServlet (for example, when using JSF or
        Struts), you need to add the following
        <code class="interfacename">javax.servlet.ServletRequestListener</code> to
        the declarations in your web applications <code class="literal">web.xml</code>
        file:</p><pre class="programlisting">&lt;<span class="hl-tag">web-app</span>&gt;
...
&lt;<span class="hl-tag">listener</span>&gt;
  &lt;<span class="hl-tag">listener-class</span>&gt;
      org.springframework.web.context.request.RequestContextListener
  &lt;<span class="hl-tag">/listener-class</span>&gt;
&lt;<span class="hl-tag">/listener</span>&gt;
...
&lt;<span class="hl-tag">/web-app</span>&gt;</pre><p>If you use an older web container (Servlet 2.3), use the provided
        <code class="interfacename">javax.servlet.Filter</code> implementation. The
        following snippet of XML configuration must be included in the
        <code class="literal">web.xml</code> file of your web application if you want to
        access web-scoped beans in requests outside of Spring's
        DispatcherServlet on a Servlet 2.3 container. (The filter mapping
        depends on the surrounding web application configuration, so you must
        change it as appropriate.)</p><pre class="programlisting">&lt;<span class="hl-tag">web-app</span>&gt;
..
&lt;<span class="hl-tag">filter</span>&gt;
  &lt;<span class="hl-tag">filter-name</span>&gt;requestContextFilter&lt;<span class="hl-tag">/filter-name</span>&gt;
  &lt;<span class="hl-tag">filter-class</span>&gt;org.springframework.web.filter.RequestContextFilter&lt;<span class="hl-tag">/filter-class</span>&gt;
&lt;<span class="hl-tag">/filter</span>&gt;
&lt;<span class="hl-tag">filter-mapping</span>&gt;
  &lt;<span class="hl-tag">filter-name</span>&gt;requestContextFilter&lt;<span class="hl-tag">/filter-name</span>&gt;
  &lt;<span class="hl-tag">url-pattern</span>&gt;/*&lt;<span class="hl-tag">/url-pattern</span>&gt;
&lt;<span class="hl-tag">/filter-mapping</span>&gt;
...
&lt;<span class="hl-tag">/web-app</span>&gt;</pre><p><code class="classname">DispatcherServlet</code>,
        <code class="classname">RequestContextListener</code> and
        <code class="classname">RequestContextFilter</code> all do exactly the same
        thing, namely bind the HTTP request object to the
        <code class="classname">Thread</code> that is servicing that request. This makes
        beans that are request- and session-scoped available further down the
        call chain.</p></div><div class="section" lang="en"><div class="titlepage"><div><div><h4 class="title"><a name="beans-factory-scopes-request"></a>4.5.4.2&nbsp;Request scope</h4></div></div></div><p>Consider the following bean definition:</p><pre class="programlisting">&lt;<span class="hl-tag">bean</span> <span class="hl-attribute">id</span>=<span class="hl-value">"loginAction"</span> <span class="hl-attribute">class</span>=<span class="hl-value">"com.foo.LoginAction"</span> <span class="hl-attribute">scope</span>=<span class="hl-value">"request"</span>/&gt;</pre><p>The Spring container creates a new instance of the
        <code class="classname">LoginAction</code> bean by using the
        <code class="literal">loginAction</code> bean definition for each and every HTTP
        request. That is, the <code class="literal">loginAction</code> bean is scoped at
        the HTTP request level. You can change the internal state of the
        instance that is created as much as you want, because other instances
        created from the same <code class="literal">loginAction</code> bean definition
        will not see these changes in state; they are particular to an
        individual request. When the request completes processing, the bean that
        is scoped to the request is discarded.</p></div><div class="section" lang="en"><div class="titlepage"><div><div><h4 class="title"><a name="beans-factory-scopes-session"></a>4.5.4.3&nbsp;Session scope</h4></div></div></div><p>Consider the following bean definition:</p><pre class="programlisting">&lt;<span class="hl-tag">bean</span> <span class="hl-attribute">id</span>=<span class="hl-value">"userPreferences"</span> <span class="hl-attribute">class</span>=<span class="hl-value">"com.foo.UserPreferences"</span> <span class="hl-attribute">scope</span>=<span class="hl-value">"session"</span>/&gt;</pre><p>The Spring container creates a new instance of the
        <code class="classname">UserPreferences</code> bean by using the
        <code class="literal">userPreferences</code> bean definition for the lifetime of a
        single HTTP <code class="interfacename">Session</code>. In other words, the
        <code class="literal">userPreferences</code> bean is effectively scoped at the
        HTTP <code class="interfacename">Session</code> level. As with
        <code class="literal">request-scoped</code> beans, you can change the internal
        state of the instance that is created as much as you want, knowing that
        other HTTP <code class="interfacename">Session</code> instances that are
        also using instances created from the same
        <code class="literal">userPreferences</code> bean definition do not see these
        changes in state, because they are particular to an individual HTTP
        <code class="interfacename">Session</code>. When the HTTP
        <code class="interfacename">Session</code> is eventually discarded, the bean
        that is scoped to that particular HTTP
        <code class="interfacename">Session</code> is also discarded.</p></div><div class="section" lang="en"><div class="titlepage"><div><div><h4 class="title"><a name="beans-factory-scopes-global-session"></a>4.5.4.4&nbsp;Global session scope</h4></div></div></div><p>Consider the following bean definition:</p><pre class="programlisting">&lt;<span class="hl-tag">bean</span> <span class="hl-attribute">id</span>=<span class="hl-value">"userPreferences"</span> <span class="hl-attribute">class</span>=<span class="hl-value">"com.foo.UserPreferences"</span> <span class="hl-attribute">scope</span>=<span class="hl-value">"globalSession"</span>/&gt;</pre><p>The <code class="literal">global session</code> scope is similar to the
        standard HTTP <code class="interfacename">Session</code> scope (<a class="link" href="beans.html#beans-factory-scopes-session" title="4.5.4.3&nbsp;Session scope">described above</a>), and
        applies only in the context of portlet-based web applications. The
        portlet specification defines the notion of a global
        <code class="interfacename">Session</code> that is shared among all portlets
        that make up a single portlet web application. Beans defined at the
        <code class="literal">global session</code> scope are scoped (or bound) to the
        lifetime of the global portlet
        <code class="interfacename">Session</code>.</p><p>If you write a standard Servlet-based web application and you define
        one or more beans as having <code class="literal">global session</code> scope, the
        standard HTTP <code class="interfacename">Session</code> scope is used, and
        no error is raised.</p></div><div class="section" lang="en"><div class="titlepage"><div><div><h4 class="title"><a name="beans-factory-scopes-other-injection"></a>4.5.4.5&nbsp;Scoped beans as dependencies</h4></div></div></div><p>The Spring IoC container manages not only the instantiation of your
        objects (beans), but also the wiring up of collaborators (or
        dependencies). If you want to inject (for example) an HTTP request
        scoped bean into another bean, you must inject an AOP proxy in place of
        the scoped bean. That is, you need to inject a proxy object that exposes
        the same public interface as the scoped object but that can also
        retrieve the real, target object from the relevant scope (for example,
        an HTTP request) and delegate method calls onto the real object.</p><div class="note" style="margin-left: 0.5in; margin-right: 0.5in;"><table border="0" summary="Note"><tr><td rowspan="2" align="center" valign="top" width="25"><img alt="[Note]" src="images/note.gif"></td><th align="left">Note</th></tr><tr><td align="left" valign="top"><p>You <span class="emphasis"><em>do not</em></span> need to use the
          <code class="literal">&lt;aop:scoped-proxy/&gt;</code> in conjunction with beans
          that are scoped as <code class="literal">singletons</code> or
          <code class="literal">prototypes</code>. If you try to create a scoped proxy for
          a singleton bean, the
          <code class="exceptionname">BeanCreationException</code> is raised.</p></td></tr></table></div><p>The configuration in the following example is only one line, but it
        is important to understand the &#8220;<span class="quote">why</span>&#8221; as well as the
        &#8220;<span class="quote">how</span>&#8221; behind it.</p><pre class="programlisting">&lt;<span class="hl-tag">?xml version="1.0" encoding="UTF-8"?</span>&gt;
&lt;<span class="hl-tag">beans</span> <span class="hl-attribute">xmlns</span>=<span class="hl-value">"http://www.springframework.org/schema/beans"</span>
     <span class="hl-attribute">xmlns:xsi</span>=<span class="hl-value">"http://www.w3.org/2001/XMLSchema-instance"</span>
     <span class="hl-attribute">xmlns:aop</span>=<span class="hl-value">"http://www.springframework.org/schema/aop"</span>
     <span class="hl-attribute">xsi:schemaLocation</span>=<span class="hl-value">"http://www.springframework.org/schema/beans
         http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
         http://www.springframework.org/schema/aop
         http://www.springframework.org/schema/aop/spring-aop-3.0.xsd"</span>&gt;

  &lt;<span class="hl-comment">!-- an HTTP Session-scoped bean exposed as a proxy --</span>&gt;
  &lt;<span class="hl-tag">bean</span> <span class="hl-attribute">id</span>=<span class="hl-value">"userPreferences"</span> <span class="hl-attribute">class</span>=<span class="hl-value">"com.foo.UserPreferences"</span> <span class="hl-attribute">scope</span>=<span class="hl-value">"session"</span>&gt;

        &lt;<span class="hl-comment">!-- this next element effects the proxying of the surrounding bean --</span>&gt;
        &lt;<span class="hl-tag">aop:scoped-proxy</span>/&gt;
  &lt;<span class="hl-tag">/bean</span>&gt;

  &lt;<span class="hl-comment">!-- a singleton-scoped bean injected with a proxy to the above bean --</span>&gt;
  &lt;<span class="hl-tag">bean</span> <span class="hl-attribute">id</span>=<span class="hl-value">"userService"</span> <span class="hl-attribute">class</span>=<span class="hl-value">"com.foo.SimpleUserService"</span>&gt;

      &lt;<span class="hl-comment">!-- a reference to the proxied userPreferences bean --</span>&gt;
      &lt;<span class="hl-tag">property</span> <span class="hl-attribute">name</span>=<span class="hl-value">"userPreferences"</span> <span class="hl-attribute">ref</span>=<span class="hl-value">"userPreferences"</span>/&gt;

  &lt;<span class="hl-tag">/bean</span>&gt;
&lt;<span class="hl-tag">/beans</span>&gt;
</pre><p>To create such a proxy, you insert a child
        <code class="literal">&lt;aop:scoped-proxy/&gt;</code> element into a scoped bean
        definition.
        (If
        you choose class-based proxying, you also need the CGLIB library in your
        classpath. See <a class="xref" href="beans.html#beans-factory-scopes-other-injection-proxies" title="Choosing the type of proxy to create">the section called &#8220;Choosing the type of proxy to create&#8221;</a> and <a class="xref" href="xsd-config.html" title="Appendix&nbsp;C.&nbsp;XML Schema-based configuration">Appendix&nbsp;C, <i>XML Schema-based configuration</i></a>.) Why do definitions of beans scoped at the
        <code class="literal">request</code>, <code class="literal">session</code>,
        <code class="literal">globalSession</code> and custom-scope levels require the
        <code class="literal">&lt;aop:scoped-proxy/&gt;</code> element ? Let's examine the
        following singleton bean definition and contrast it with what you need
        to define for the aforementioned scopes. (The following
        <code class="literal">userPreferences</code> bean definition as it stands is
        <span class="emphasis"><em>incomplete.)</em></span></p><pre class="programlisting">&lt;<span class="hl-tag">bean</span> <span class="hl-attribute">id</span>=<span class="hl-value">"userPreferences"</span> <span class="hl-attribute">class</span>=<span class="hl-value">"com.foo.UserPreferences"</span> <span class="hl-attribute">scope</span>=<span class="hl-value">"session"</span>/&gt;

&lt;<span class="hl-tag">bean</span> <span class="hl-attribute">id</span>=<span class="hl-value">"userManager"</span> <span class="hl-attribute">class</span>=<span class="hl-value">"com.foo.UserManager"</span>&gt;
  &lt;<span class="hl-tag">property</span> <span class="hl-attribute">name</span>=<span class="hl-value">"userPreferences"</span> <span class="hl-attribute">ref</span>=<span class="hl-value">"userPreferences"</span>/&gt;
&lt;<span class="hl-tag">/bean</span>&gt;</pre><p>In the preceding example, the singleton bean
        <code class="literal">userManager</code> is injected with a reference to the HTTP
        <code class="interfacename">Session</code>-scoped bean
        <code class="literal">userPreferences</code>. The salient point here is that the
        <code class="literal">userManager</code> bean is a singleton: it will be
        instantiated <span class="emphasis"><em>exactly once</em></span> per container, and its
        dependencies (in this case only one, the
        <code class="literal">userPreferences</code> bean) are also injected only once.
        This means that the <code class="literal">userManager</code> bean will only
        operate on the exact same <code class="literal">userPreferences</code> object,
        that is, the one that it was originally injected with.</p><p>This is <span class="emphasis"><em>not</em></span> the behavior you want when
        injecting a shorter-lived scoped bean into a longer-lived scoped bean,
        for example injecting an HTTP
        <code class="interfacename">Session</code>-scoped collaborating bean as a
        dependency into singleton bean. Rather, you need a single
        <code class="literal">userManager</code> object, and for the lifetime of an HTTP
        <code class="interfacename">Session</code>, you need a
        <code class="literal">userPreferences</code> object that is specific to said HTTP
        <code class="interfacename">Session</code>. Thus the container creates an
        object that exposes the exact same public interface as the
        <code class="classname">UserPreferences</code> class (ideally an object that
        <span class="emphasis"><em>is a</em></span> <code class="classname">UserPreferences</code>
        instance) which can fetch the real
        <code class="classname">UserPreferences</code> object from the scoping mechanism
        (HTTP request, <code class="interfacename">Session</code>, etc.). The
        container injects this proxy object into the
        <code class="literal">userManager</code> bean, which is unaware that this
        <code class="classname">UserPreferences</code> reference is a proxy. In this
        example, when a <code class="interfacename">UserManager</code> instance
        invokes a method on the dependency-injected
        <code class="classname">UserPreferences</code> object, it actually is invoking a
        method on the proxy. The proxy then fetches the real
        <code class="classname">UserPreferences</code> object from (in this case) the
        HTTP <code class="interfacename">Session</code>, and delegates the method
        invocation onto the retrieved real
        <code class="classname">UserPreferences</code> object.</p><p>Thus you need the following, correct and complete, configuration
        when injecting <code class="literal">request-</code>, <code class="literal">session-</code>,
        and <code class="literal">globalSession-scoped</code> beans into collaborating
        objects:</p><pre class="programlisting">&lt;<span class="hl-tag">bean</span> <span class="hl-attribute">id</span>=<span class="hl-value">"userPreferences"</span> <span class="hl-attribute">class</span>=<span class="hl-value">"com.foo.UserPreferences"</span> <span class="hl-attribute">scope</span>=<span class="hl-value">"session"</span>&gt;
  &lt;<span class="hl-tag">aop:scoped-proxy</span>/&gt;
&lt;<span class="hl-tag">/bean</span>&gt;

&lt;<span class="hl-tag">bean</span> <span class="hl-attribute">id</span>=<span class="hl-value">"userManager"</span> <span class="hl-attribute">class</span>=<span class="hl-value">"com.foo.UserManager"</span>&gt;
  &lt;<span class="hl-tag">property</span> <span class="hl-attribute">name</span>=<span class="hl-value">"userPreferences"</span> <span class="hl-attribute">ref</span>=<span class="hl-value">"userPreferences"</span>/&gt;
&lt;<span class="hl-tag">/bean</span>&gt;</pre><div class="section" lang="en"><div class="titlepage"><div><div><h5 class="title"><a name="beans-factory-scopes-other-injection-proxies"></a>Choosing the type of proxy to create</h5></div></div></div><p>By default, when the Spring container creates a proxy for a bean
          that is marked up with the
          <code class="literal">&lt;aop:scoped-proxy/&gt;</code> element, <span class="emphasis"><em>a
          CGLIB-based class proxy is created</em></span>. This means that you
          need to have the CGLIB library in the classpath of your
          application.</p><p><span class="emphasis"><em>Note: CGLIB proxies only intercept public method
          calls!</em></span> Do not call non-public methods on such a proxy; they
          will not be delegated to the scoped target object.</p><p>Alternatively, you can configure the Spring container to create
          standard JDK interface-based proxies for such scoped beans, by
          specifying <code class="literal">false</code> for the value of the
          <code class="literal">proxy-target-class</code> attribute of the
          <code class="literal">&lt;aop:scoped-proxy/&gt;</code> element. Using JDK
          interface-based proxies means that you do not need additional
          libraries in your application classpath to effect such proxying.
          However, it also means that the class of the scoped bean must
          implement at least one interface, and <span class="emphasis"><em>that all</em></span>
          collaborators into which the scoped bean is injected must reference
          the bean through one of its interfaces.</p><pre class="programlisting">&lt;<span class="hl-comment">!-- DefaultUserPreferences implements the UserPreferences interface --</span>&gt;
&lt;<span class="hl-tag">bean</span> <span class="hl-attribute">id</span>=<span class="hl-value">"userPreferences"</span> <span class="hl-attribute">class</span>=<span class="hl-value">"com.foo.DefaultUserPreferences"</span> <span class="hl-attribute">scope</span>=<span class="hl-value">"session"</span>&gt;
  &lt;<span class="hl-tag">aop:scoped-proxy</span> <span class="hl-attribute">proxy-target-class</span>=<span class="hl-value">"false"</span>/&gt;
&lt;<span class="hl-tag">/bean</span>&gt;

&lt;<span class="hl-tag">bean</span> <span class="hl-attribute">id</span>=<span class="hl-value">"userManager"</span> <span class="hl-attribute">class</span>=<span class="hl-value">"com.foo.UserManager"</span>&gt;
  &lt;<span class="hl-tag">property</span> <span class="hl-attribute">name</span>=<span class="hl-value">"userPreferences"</span> <span class="hl-attribute">ref</span>=<span class="hl-value">"userPreferences"</span>/&gt;
&lt;<span class="hl-tag">/bean</span>&gt;</pre><p>For more detailed information about choosing class-based or
          interface-based proxying, see <a class="xref" href="aop.html#aop-proxying" title="8.6&nbsp;Proxying mechanisms">Section&nbsp;8.6, &#8220;Proxying mechanisms&#8221;</a>.</p></div></div></div><div class="section" lang="en"><div class="titlepage"><div><div><h3 class="title"><a name="beans-factory-scopes-custom"></a>4.5.5&nbsp;Custom scopes</h3></div></div></div><p>As of Spring 2.0, the bean scoping mechanism is extensible. You can
      define your own scopes, or even redefine existing scopes, although the
      latter is considered bad practice and you <span class="emphasis"><em>cannot</em></span>
      override the built-in <code class="literal">singleton</code> and
      <code class="literal">prototype</code> scopes.</p><div class="section" lang="en"><div class="titlepage"><div><div><h4 class="title"><a name="beans-factory-scopes-custom-creating"></a>4.5.5.1&nbsp;Creating a custom scope</h4></div></div></div><p>To integrate your custom scope(s) into the Spring container, you
        need to implement the
        <code class="interfacename">org.springframework.beans.factory.config.Scope</code>
        interface, which is described in this section. For an idea of how to
        implement your own scopes, see the <code class="interfacename">Scope</code>
        implementations that are supplied with the Spring Framework itself and
        the <a class="ulink" href="http://static.springframework.org/spring/docs/3.0.x/javadoc-api/org/springframework/beans/factory/config/Scope.html" target="_top">Scope Javadoc</a>, which explains the methods you need to implement
        in more detail.</p><p>The <code class="literal">Scope</code> interface has four methods to get
        objects from the scope, remove them from the scope, and allow them to be
        destroyed.</p><p>The following method returns the object from the underlying scope.
        The session scope implementation, for example, returns the
        session-scoped bean (and if it does not exist, the method returns a new
        instance of the bean, after having bound it to the session for future
        reference).</p><pre class="programlisting">Object get(String name, ObjectFactory objectFactory)</pre><p>The following method removes the object from the underlying scope.
        The session scope implementation for example, removes the session-scoped
        bean from the underlying session. The object should be returned, but you
        can return null if the object with the specified name is not
        found.</p><pre class="programlisting">Object remove(String name)</pre><p>The following method registers the callbacks the scope should
        execute when it is destroyed or when the specified object in the scope
        is destroyed. Refer to the Javadoc or a Spring scope implementation for
        more information on destruction callbacks.</p><pre class="programlisting"><span class="hl-keyword">void</span> registerDestructionCallback(String name, Runnable destructionCallback)</pre><p>The following method obtains the conversation identifier for the
        underlying scope. This identifier is different for each scope. For a
        session scoped implementation, this identifier can be the session
        identifier.</p><pre class="programlisting">String getConversationId()</pre></div><div class="section" lang="en"><div class="titlepage"><div><div><h4 class="title"><a name="beans-factory-scopes-custom-using"></a>4.5.5.2&nbsp;Using a custom scope</h4></div></div></div><p>After you write and test one or more custom
        <code class="interfacename">Scope</code> implementations, you need to make
        the Spring container aware of your new scope(s). The following method is
        the central method to register a new
        <code class="interfacename">Scope</code> with the Spring container:</p><pre class="programlisting"><span class="hl-keyword">void</span> registerScope(String scopeName, Scope scope);</pre><p>This method is declared on the
        <code class="interfacename">ConfigurableBeanFactory</code> interface, which
        is available on most of the concrete
        <code class="interfacename">ApplicationContext</code> implementations that
        ship with Spring via the BeanFactory property.</p><p>The first argument to the <code class="methodname">registerScope(..)</code>
        method is the unique name associated with a scope; examples of such
        names in the Spring container itself are <code class="literal">singleton</code>
        and <code class="literal">prototype</code>. The second argument to the
        <code class="methodname">registerScope(..)</code> method is an actual instance
        of the custom <code class="interfacename">Scope</code> implementation that
        you wish to register and use.</p><p>Suppose that you write your custom
        <code class="interfacename">Scope</code> implementation, and then register
        it as below.</p><div class="note" style="margin-left: 0.5in; margin-right: 0.5in;"><table border="0" summary="Note"><tr><td rowspan="2" align="center" valign="top" width="25"><img alt="[Note]" src="images/note.gif"></td><th align="left">Note</th></tr><tr><td align="left" valign="top"><p>The example below uses <code class="literal">SimpleThreadScope</code> which
          is included with Spring, but not registered by default. The
          instructions would be the same for your own custom
          <code class="literal">Scope</code> implementations.</p></td></tr></table></div><pre class="programlisting">
Scope threadScope = <span class="hl-keyword">new</span> SimpleThreadScope();
beanFactory.registerScope(<span class="hl-string">"thread"</span>, threadScope);</pre><p>You then create bean definitions that adhere to the scoping rules of
        your custom <code class="interfacename">Scope</code>:</p><pre class="programlisting">&lt;<span class="hl-tag">bean</span> <span class="hl-attribute">id</span>=<span class="hl-value">"..."</span> <span class="hl-attribute">class</span>=<span class="hl-value">"..."</span> <span class="hl-attribute">scope</span>=<span class="hl-value">"thread"</span>&gt;</pre><p>With a custom <code class="interfacename">Scope</code> implementation,
        you are not limited to programmatic registration of the scope. You can
        also do the <code class="interfacename">Scope</code> registration
        declaratively, using the <code class="classname">CustomScopeConfigurer</code>
        class:</p><pre class="programlisting">&lt;<span class="hl-tag">?xml version="1.0" encoding="UTF-8"?</span>&gt;
&lt;<span class="hl-tag">beans</span> <span class="hl-attribute">xmlns</span>=<span class="hl-value">"http://www.springframework.org/schema/beans"</span>
     <span class="hl-attribute">xmlns:xsi</span>=<span class="hl-value">"http://www.w3.org/2001/XMLSchema-instance"</span>
     <span class="hl-attribute">xmlns:aop</span>=<span class="hl-value">"http://www.springframework.org/schema/aop"</span>
     <span class="hl-attribute">xsi:schemaLocation</span>=<span class="hl-value">"http://www.springframework.org/schema/beans
         http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
         http://www.springframework.org/schema/aop
         http://www.springframework.org/schema/aop/spring-aop-3.0.xsd"</span>&gt;

  &lt;<span class="hl-tag">bean</span> <span class="hl-attribute">class</span>=<span class="hl-value">"org.springframework.beans.factory.config.CustomScopeConfigurer"</span>&gt;
      &lt;<span class="hl-tag">property</span> <span class="hl-attribute">name</span>=<span class="hl-value">"scopes"</span>&gt;
          &lt;<span class="hl-tag">map</span>&gt;
              &lt;<span class="hl-tag">entry</span> <span class="hl-attribute">key</span>=<span class="hl-value">"thread"</span>&gt;
                  &lt;<span class="hl-tag">bean</span> <span class="hl-attribute">class</span>=<span class="hl-value">"org.springframework.context.support.SimpleThreadScope"</span>/&gt;
              &lt;<span class="hl-tag">/entry</span>&gt;
          &lt;<span class="hl-tag">/map</span>&gt;
      &lt;<span class="hl-tag">/property</span>&gt;
  &lt;<span class="hl-tag">/bean</span>&gt;

  &lt;<span class="hl-tag">bean</span> <span class="hl-attribute">id</span>=<span class="hl-value">"bar"</span> <span class="hl-attribute">class</span>=<span class="hl-value">"x.y.Bar"</span> <span class="hl-attribute">scope</span>=<span class="hl-value">"thread"</span>&gt;
      &lt;<span class="hl-tag">property</span> <span class="hl-attribute">name</span>=<span class="hl-value">"name"</span> <span class="hl-attribute">value</span>=<span class="hl-value">"Rick"</span>/&gt;
      &lt;<span class="hl-tag">aop:scoped-proxy</span>/&gt;
  &lt;<span class="hl-tag">/bean</span>&gt;

  &lt;<span class="hl-tag">bean</span> <span class="hl-attribute">id</span>=<span class="hl-value">"foo"</span> <span class="hl-attribute">class</span>=<span class="hl-value">"x.y.Foo"</span>&gt;
      &lt;<span class="hl-tag">property</span> <span class="hl-attribute">name</span>=<span class="hl-value">"bar"</span> <span class="hl-attribute">ref</span>=<span class="hl-value">"bar"</span>/&gt;
  &lt;<span class="hl-tag">/bean</span>&gt;

&lt;<span class="hl-tag">/beans</span>&gt;</pre><div class="note" style="margin-left: 0.5in; margin-right: 0.5in;"><table border="0" summary="Note"><tr><td rowspan="2" align="center" valign="top" width="25"><img alt="[Note]" src="images/note.gif"></td><th align="left">Note</th></tr><tr><td align="left" valign="top"><p>When you place &lt;aop:scoped-proxy/&gt; in a
          <code class="interfacename">FactoryBean</code> implementation, it is the
          factory bean itself that is scoped, not the object returned from
          <code class="methodname">getObject()</code>.</p></td></tr></table></div></div></div></div><div class="section" lang="en"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="beans-factory-nature"></a>4.6&nbsp;Customizing the nature of a bean</h2></div></div></div><div class="section" lang="en"><div class="titlepage"><div><div><h3 class="title"><a name="beans-factory-lifecycle"></a>4.6.1&nbsp;Lifecycle callbacks</h3></div></div></div><p>To interact with the container's management of the bean lifecycle, you
      can implement the Spring <code class="interfacename">InitializingBean</code>
      and <code class="interfacename">DisposableBean</code> interfaces. The
      container calls <code class="methodname">afterPropertiesSet()</code> for the
      former and <code class="methodname">destroy()</code> for the latter to allow the
      bean to perform certain actions upon initialization and destruction of
      your beans. You can also achieve the same integration with the container
      without coupling your classes to Spring interfaces through the use of
      init-method and destroy method object definition metadata.</p><p>Internally, the Spring Framework uses
      <code class="interfacename">BeanPostProcessor</code> implementations to
      process any callback interfaces it can find and call the appropriate
      methods. If you need custom features or other lifecycle behavior Spring
      does not offer out-of-the-box, you can implement a
      <code class="interfacename">BeanPostProcessor</code> yourself. For more
      information, see <a class="xref" href="beans.html#beans-factory-extension" title="4.8&nbsp;Container Extension Points">Section&nbsp;4.8, &#8220;Container Extension Points&#8221;</a>.</p><p>In addition to the initialization and destruction callbacks,
      Spring-managed objects may also implement the
      <code class="interfacename">Lifecycle</code> interface so that those objects
      can participate in the startup and shutdown process as driven by the
      container's own lifecycle.</p><p>The lifecycle callback interfaces are described in this
      section.</p><div class="section" lang="en"><div class="titlepage"><div><div><h4 class="title"><a name="beans-factory-lifecycle-initializingbean"></a>4.6.1.1&nbsp;Initialization callbacks</h4></div></div></div><p>The
        <code class="interfacename">org.springframework.beans.factory.InitializingBean</code>
        interface allows a bean to perform initialization work after all
        necessary properties on the bean have been set by the container. The
        <code class="interfacename">InitializingBean</code> interface specifies a
        single method:</p><pre class="programlisting"><span class="hl-keyword">void</span> afterPropertiesSet() <span class="hl-keyword">throws</span> Exception;</pre><p>It is recommended that you do not use the
        <code class="interfacename">InitializingBean</code> interface because it
        unnecessarily couples the code to Spring. Alternatively, specify a POJO
        initialization method. In the case of XML-based configuration metadata,
        you use the <code class="literal">init-method</code> attribute to specify the name
        of the method that has a void no-argument signature. For example, the
        following definition:</p><pre class="programlisting">&lt;<span class="hl-tag">bean</span> <span class="hl-attribute">id</span>=<span class="hl-value">"exampleInitBean"</span> <span class="hl-attribute">class</span>=<span class="hl-value">"examples.ExampleBean"</span> <span class="hl-attribute">init-method</span>=<span class="hl-value">"init"</span>/&gt;</pre><pre class="programlisting"><span class="hl-keyword">public</span> <span class="hl-keyword">class</span> ExampleBean {

  <span class="hl-keyword">public</span> <span class="hl-keyword">void</span> init() {
      <span class="hl-comment">// do some initialization work</span>
  }
}</pre><p>...is exactly the same as...</p><pre class="programlisting">&lt;<span class="hl-tag">bean</span> <span class="hl-attribute">id</span>=<span class="hl-value">"exampleInitBean"</span> <span class="hl-attribute">class</span>=<span class="hl-value">"examples.AnotherExampleBean"</span>/&gt;</pre><pre class="programlisting"><span class="hl-keyword">public</span> <span class="hl-keyword">class</span> AnotherExampleBean <span class="hl-keyword">implements</span> InitializingBean {

  <span class="hl-keyword">public</span> <span class="hl-keyword">void</span> afterPropertiesSet() {
      <span class="hl-comment">// do some initialization work</span>
  }
}</pre><p>... but does not couple the code to Spring.</p></div><div class="section" lang="en"><div class="titlepage"><div><div><h4 class="title"><a name="beans-factory-lifecycle-disposablebean"></a>4.6.1.2&nbsp;Destruction callbacks</h4></div></div></div><p>Implementing the
        <code class="interfacename">org.springframework.beans.factory.DisposableBean</code>
        interface allows a bean to get a callback when the container containing
        it is destroyed. The <code class="interfacename">DisposableBean</code>
        interface specifies a single method:</p><pre class="programlisting"><span class="hl-keyword">void</span> destroy() <span class="hl-keyword">throws</span> Exception;</pre><p>It is recommended that you do not use the
        <code class="interfacename">DisposableBean</code> callback interface because
        it unnecessarily couples the code to Spring. Alternatively, specify a
        generic method that is supported by bean definitions. With XML-based
        configuration metadata, you use the <code class="literal">destroy-method</code>
        attribute on the <code class="literal">&lt;bean/&gt;</code>. For example, the
        following definition:</p><pre class="programlisting">&lt;<span class="hl-tag">bean</span> <span class="hl-attribute">id</span>=<span class="hl-value">"exampleInitBean"</span> <span class="hl-attribute">class</span>=<span class="hl-value">"examples.ExampleBean"</span> <span class="hl-attribute">destroy-method</span>=<span class="hl-value">"cleanup"</span>/&gt;</pre><pre class="programlisting"><span class="hl-keyword">public</span> <span class="hl-keyword">class</span> ExampleBean {

  <span class="hl-keyword">public</span> <span class="hl-keyword">void</span> cleanup() {
      <span class="hl-comment">// do some destruction work (like releasing pooled connections)</span>
  }
}</pre><p>...is exactly the same as...</p><pre class="programlisting">&lt;<span class="hl-tag">bean</span> <span class="hl-attribute">id</span>=<span class="hl-value">"exampleInitBean"</span> <span class="hl-attribute">class</span>=<span class="hl-value">"examples.AnotherExampleBean"</span>/&gt;</pre><pre class="programlisting"><span class="hl-keyword">public</span> <span class="hl-keyword">class</span> AnotherExampleBean <span class="hl-keyword">implements</span> DisposableBean {

  <span class="hl-keyword">public</span> <span class="hl-keyword">void</span> destroy() {
      <span class="hl-comment">// do some destruction work (like releasing pooled connections)</span>
  }
}</pre><p>... but does not couple the code to Spring.</p></div><div class="section" lang="en"><div class="titlepage"><div><div><h4 class="title"><a name="beans-factory-lifecycle-default-init-destroy-methods"></a>4.6.1.3&nbsp;Default initialization and destroy methods</h4></div></div></div><p>When you write initialization and destroy method callbacks that do
        not use the Spring-specific
        <code class="interfacename">InitializingBean</code> and
        <code class="interfacename">DisposableBean</code> callback interfaces, you
        typically write methods with names such as <code class="literal">init()</code>,
        <code class="literal">initialize()</code>, <code class="literal">dispose()</code>, and so
        on. Ideally, the names of such lifecycle callback methods are
        standardized across a project so that all developers use the same method
        names and ensure consistency.</p><p>You can configure the Spring container to <code class="literal">look</code>
        for named initialization and destroy callback method names on
        <span class="emphasis"><em>every</em></span> bean. This means that you, as an application
        developer, can write your application classes and use an initialization
        callback called <code class="literal">init()</code>, without having to configure
        an <code class="literal">init-method="init"</code> attribute with each bean
        definition. The Spring IoC container calls that method when the bean is
        created (and in accordance with the standard lifecycle callback contract
        described previously). This feature also enforces a consistent naming
        convention for initialization and destroy method callbacks.</p><p>Suppose that your initialization callback methods are named
        <code class="literal">init()</code> and destroy callback methods are named
        <code class="literal">destroy()</code>. Your class will resemble the class in the
        following example.</p><pre class="programlisting"><span class="hl-keyword">public</span> <span class="hl-keyword">class</span> DefaultBlogService <span class="hl-keyword">implements</span> BlogService {

  <span class="hl-keyword">private</span> BlogDao blogDao;

  <span class="hl-keyword">public</span> <span class="hl-keyword">void</span> setBlogDao(BlogDao blogDao) {
      <span class="hl-keyword">this</span>.blogDao = blogDao;
  }

  <span class="hl-comment">// this is (unsurprisingly) the initialization callback method</span>
  <span class="hl-keyword">public</span> <span class="hl-keyword">void</span> init() {
      <span class="hl-keyword">if</span> (<span class="hl-keyword">this</span>.blogDao == null) {
          <span class="hl-keyword">throw</span> <span class="hl-keyword">new</span> IllegalStateException(<span class="hl-string">"The [blogDao] property must be set."</span>);
      }
  }
}</pre><pre class="programlisting">&lt;<span class="hl-tag">beans</span> <span class="hl-attribute">default-init-method</span>=<span class="hl-value">"init"</span>&gt;

  &lt;<span class="hl-tag">bean</span> <span class="hl-attribute">id</span>=<span class="hl-value">"blogService"</span> <span class="hl-attribute">class</span>=<span class="hl-value">"com.foo.DefaultBlogService"</span>&gt;
      &lt;<span class="hl-tag">property</span> <span class="hl-attribute">name</span>=<span class="hl-value">"blogDao"</span> <span class="hl-attribute">ref</span>=<span class="hl-value">"blogDao"</span> /&gt;
  &lt;<span class="hl-tag">/bean</span>&gt;

&lt;<span class="hl-tag">/beans</span>&gt;</pre><p>The presence of the <code class="literal">default-init-method</code> attribute
        on the top-level <code class="literal">&lt;beans/&gt;</code> element attribute
        causes the Spring IoC container to recognize a method called
        <code class="literal">init</code> on beans as the initialization method callback.
        When a bean is created and assembled, if the bean class has such a
        method, it is invoked at the appropriate time.</p><p>You configure destroy method callbacks similarly (in XML, that is)
        by using the <code class="literal">default-destroy-method</code> attribute on the
        top-level <code class="literal">&lt;beans/&gt;</code> element.</p><p>Where existing bean classes already have callback methods that are
        named at variance with the convention, you can override the default by
        specifying (in XML, that is) the method name using the
        <code class="literal">init-method</code> and <code class="literal">destroy-method</code>
        attributes of the &lt;bean/&gt; itself.</p><p>The Spring container guarantees that a configured initialization
        callback is called immediately after a bean is supplied with all
        dependencies. Thus the initialization callback is called on the raw bean
        reference, which means that AOP interceptors and so forth are not yet
        applied to the bean. A target bean is fully created
        <span class="emphasis"><em>first</em></span>, <span class="emphasis"><em>then</em></span> an AOP proxy (for
        example) with its interceptor chain is applied. If the target bean and
        the proxy are defined separately, your code can even interact with the
        raw target bean, bypassing the proxy. Hence, it would be inconsistent to
        apply the interceptors to the init method, because doing so would couple
        the lifecycle of the target bean with its proxy/interceptors and leave
        strange semantics when your code interacts directly to the raw target
        bean.</p></div><div class="section" lang="en"><div class="titlepage"><div><div><h4 class="title"><a name="beans-factory-lifecycle-combined-effects"></a>4.6.1.4&nbsp;Combining lifecycle mechanisms</h4></div></div></div><p>As of Spring 2.5, you have three options for controlling bean
        lifecycle behavior: the <a class="link" href="beans.html#beans-factory-lifecycle-initializingbean" title="4.6.1.1&nbsp;Initialization callbacks"><code class="interfacename">InitializingBean</code></a> and <a class="link" href="beans.html#beans-factory-lifecycle-disposablebean" title="4.6.1.2&nbsp;Destruction callbacks"><code class="interfacename">DisposableBean</code></a> callback
        interfaces; custom <code class="literal">init()</code> and
        <code class="literal">destroy()</code> methods; and the <a class="link" href="beans.html#beans-postconstruct-and-predestroy-annotations" title="4.9.6&nbsp;@PostConstruct and @PreDestroy"><code class="interfacename">@PostConstruct</code> and
        <code class="interfacename">@PreDestroy</code> annotations</a>. You can
        combine these mechanisms to control a given bean.</p><div class="note" style="margin-left: 0.5in; margin-right: 0.5in;"><table border="0" summary="Note"><tr><td rowspan="2" align="center" valign="top" width="25"><img alt="[Note]" src="images/note.gif"></td><th align="left">Note</th></tr><tr><td align="left" valign="top"><p>If multiple lifecycle mechanisms are configured for a bean, and
          each mechanism is configured with a different method name, then each
          configured method is executed in the order listed below. However, if
          the same method name is configured - for example,
          <code class="literal">init()</code> for an initialization method - for more than
          one of these lifecycle mechanisms, that method is executed once, as
          explained in the preceding section.</p></td></tr></table></div><p>Multiple lifecycle mechanisms configured for the same bean, with
        different initialization methods, are called as follows:</p><div class="itemizedlist"><ul type="disc"><li><p>Methods annotated with
            <code class="interfacename">@PostConstruct</code></p></li><li><p><code class="literal">afterPropertiesSet()</code> as defined by the
            <code class="interfacename">InitializingBean</code> callback
            interface</p></li><li><p>A custom configured <code class="literal">init()</code> method</p></li></ul></div><p>Destroy methods are called in the same order:</p><div class="itemizedlist"><ul type="disc"><li><p>Methods annotated with
            <code class="interfacename">@PreDestroy</code></p></li><li><p><code class="literal">destroy()</code> as defined by the
            <code class="interfacename">DisposableBean</code> callback
            interface</p></li><li><p>A custom configured <code class="literal">destroy()</code> method</p></li></ul></div></div><div class="section" lang="en"><div class="titlepage"><div><div><h4 class="title"><a name="beans-factory-lifecycle-processor"></a>4.6.1.5&nbsp;Startup and shutdown callbacks</h4></div></div></div><p>The <code class="interfacename">Lifecycle</code> interface defines the
        essential methods for any object that has its own lifecycle requirements
        (e.g. starts and stops some background process):</p><pre class="programlisting"><span class="hl-keyword">public</span> <span class="hl-keyword">interface</span> Lifecycle {

  <span class="hl-keyword">void</span> start();

  <span class="hl-keyword">void</span> stop();

  <span class="hl-keyword">boolean</span> isRunning();

}</pre><p>Any Spring-managed object may implement that interface. Then, when
        the ApplicationContext itself starts and stops, it will cascade those
        calls to all Lifecycle implementations defined within that context. It
        does this by delegating to a
        <code class="interfacename">LifecycleProcessor</code>:</p><pre class="programlisting"><span class="hl-keyword">public</span> <span class="hl-keyword">interface</span> LifecycleProcessor <span class="hl-keyword">extends</span> Lifecycle {

  <span class="hl-keyword">void</span> onRefresh();

  <span class="hl-keyword">void</span> onClose();

}</pre><p>Notice that the <code class="interfacename">LifecycleProcessor</code> is
        itself an extension of the <code class="interfacename">Lifecycle</code>
        interface. It also adds two other methods for reacting to the context
        being refreshed and closed.</p><p>The order of startup and shutdown invocations can be important. If a
        "depends-on" relationship exists between any two objects, the dependent
        side will start <span class="emphasis"><em>after</em></span> its dependency, and it will
        stop <span class="emphasis"><em>before</em></span> its dependency. However, at times the
        direct dependencies are unknown. You may only know that objects of a
        certain type should start prior to objects of another type. In those
        cases, the <code class="interfacename">SmartLifecycle</code> interface
        defines another option, namely the <code class="methodname">getPhase()</code>
        method as defined on its super-interface,
        <code class="interfacename">Phased</code>.</p><pre class="programlisting"><span class="hl-keyword">public</span> <span class="hl-keyword">interface</span> Phased {

  <span class="hl-keyword">int</span> getPhase();

}


<span class="hl-keyword">public</span> <span class="hl-keyword">interface</span> SmartLifecycle <span class="hl-keyword">extends</span> Lifecycle, Phased {

  <span class="hl-keyword">boolean</span> isAutoStartup();

  <span class="hl-keyword">void</span> stop(Runnable callback);

}</pre><p>When starting, the objects with the lowest phase start first, and
        when stopping, the reverse order is followed. Therefore, an object that
        implements <code class="interfacename">SmartLifecycle</code> and whose
        getPhase() method returns <code class="literal">Integer.MIN_VALUE</code> would be
        among the first to start and the last to stop. At the other end of the
        spectrum, a phase value of <code class="literal">Integer.MAX_VALUE</code> would
        indicate that the object should be started last and stopped first
        (likely because it depends on other processes to be running). When
        considering the phase value, it's also important to know that the
        default phase for any "normal" <code class="interfacename">Lifecycle</code>
        object that does not implement
        <code class="interfacename">SmartLifecycle</code> would be 0. Therefore, any
        negative phase value would indicate that an object should start before
        those standard components (and stop after them), and vice versa for any
        positive phase value.</p><p>As you can see the stop method defined by
        <code class="interfacename">SmartLifecycle</code> accepts a callback. Any
        implementation <span class="emphasis"><em>must</em></span> invoke that callback's run()
        method after that implementation's shutdown process is complete. That
        enables asynchronous shutdown where necessary since the default
        implementation of the <code class="interfacename">LifecycleProcessor</code>
        interface, <code class="classname">DefaultLifecycleProcessor</code>, will wait
        up to its timeout value for the group of objects within each phase to
        invoke that callback. The default per-phase timeout is 30 seconds. You
        can override the default lifecycle processor instance by defining a bean
        named "lifecycleProcessor" within the context. If you only want to
        modify the timeout, then defining the following would be
        sufficient:</p><pre class="programlisting">&lt;<span class="hl-tag">bean</span> <span class="hl-attribute">id</span>=<span class="hl-value">"lifecycleProcessor"</span> <span class="hl-attribute">class</span>=<span class="hl-value">"org.springframework.context.support.DefaultLifecycleProcessor"</span>&gt;
  &lt;<span class="hl-comment">!-- timeout value in milliseconds --</span>&gt;
  &lt;<span class="hl-tag">property</span> <span class="hl-attribute">name</span>=<span class="hl-value">"timeoutPerShutdownPhase"</span> <span class="hl-attribute">value</span>=<span class="hl-value">"10000"</span>/&gt;
&lt;<span class="hl-tag">/bean</span>&gt;</pre><p>As mentioned, the <code class="interfacename">LifecycleProcessor</code>
        interface defines callback methods for the refreshing and closing of the
        context as well. The latter will simply drive the shutdown process as if
        stop() had been called explicitly, but it will happen when the context
        is closing. The 'refresh' callback on the other hand enables another
        feature of <code class="interfacename">SmartLifecycle</code> beans. When the
        context is refreshed (after all objects have been instantiated and
        initialized), that callback will be invoked, and at that point the
        default lifecycle processor will check the boolean value returned by
        each <code class="interfacename">SmartLifecycle</code> object's
        <code class="methodname">isAutoStartup()</code> method. If "true", then that
        object will be started at that point rather than waiting for an explicit
        invocation of the context's or its own start() method (unlike the
        context refresh, the context start does not happen automatically for a
        standard context implementation). The "phase" value as well as any
        "depends-on" relationships will determine the startup order in the same
        way as described above.</p></div><div class="section" lang="en"><div class="titlepage"><div><div><h4 class="title"><a name="beans-factory-shutdown"></a>4.6.1.6&nbsp;Shutting down the Spring IoC container gracefully in non-web
        applications</h4></div></div></div><div class="note" style="margin-left: 0.5in; margin-right: 0.5in;"><table border="0" summary="Note"><tr><td rowspan="2" align="center" valign="top" width="25"><img alt="[Note]" src="images/note.gif"></td><th align="left">Note</th></tr><tr><td align="left" valign="top"><p>This section applies only to non-web applications. Spring's
          web-based <code class="interfacename">ApplicationContext</code>
          implementations already have code in place to shut down the Spring IoC
          container gracefully when the relevant web application is shut
          down.</p></td></tr></table></div><p>If you are using Spring's IoC container in a non-web application
        environment; for example, in a rich client desktop environment; you
        register a shutdown hook with the JVM. Doing so ensures a graceful
        shutdown and calls the relevant destroy methods on your singleton beans
        so that all resources are released. Of course, you must still configure
        and implement these destroy callbacks correctly.</p><p>To register a shutdown hook, you call the
        <code class="methodname">registerShutdownHook()</code> method that is declared
        on the <code class="classname">AbstractApplicationContext</code> class:</p><pre class="programlisting"><span class="hl-keyword">import</span> org.springframework.context.support.AbstractApplicationContext;
<span class="hl-keyword">import</span> org.springframework.context.support.ClassPathXmlApplicationContext;

<span class="hl-keyword">public</span> <span class="hl-keyword">final</span> <span class="hl-keyword">class</span> Boot {

  <span class="hl-keyword">public</span> <span class="hl-keyword">static</span> <span class="hl-keyword">void</span> main(<span class="hl-keyword">final</span> String[] args) <span class="hl-keyword">throws</span> Exception {
      AbstractApplicationContext ctx
          = <span class="hl-keyword">new</span> ClassPathXmlApplicationContext(<span class="hl-keyword">new</span> String []{<span class="hl-string">"beans.xml"</span>});

      <span class="hl-comment">// add a shutdown hook for the above context... </span>
      ctx.registerShutdownHook();

      <span class="hl-comment">// app runs here...</span>

      <span class="hl-comment">// main method exits, hook is called prior to the app shutting down...</span>
  }
}</pre></div></div><div class="section" lang="en"><div class="titlepage"><div><div><h3 class="title"><a name="beans-factory-aware"></a>4.6.2&nbsp;<code class="interfacename">ApplicationContextAware</code> and
      <code class="interfacename">BeanNameAware</code></h3></div></div></div><p>When an <code class="interfacename">ApplicationContext</code> creates a
      class that implements the
      <code class="interfacename">org.springframework.context.ApplicationContextAware</code>
      interface, the class is provided with a reference to that
      <code class="interfacename">ApplicationContext</code>.</p><pre class="programlisting"><span class="hl-keyword">public</span> <span class="hl-keyword">interface</span> ApplicationContextAware {

  <span class="hl-keyword">void</span> setApplicationContext(ApplicationContext applicationContext) <span class="hl-keyword">throws</span> BeansException;
}</pre><p>Thus beans can manipulate programmatically the
      <code class="interfacename">ApplicationContext</code> that created them,
      through the <code class="interfacename">ApplicationContext</code> interface,
      or by casting the reference to a known subclass of this interface, such as
      <code class="classname">ConfigurableApplicationContext</code>, which exposes
      additional functionality. One use would be the programmatic retrieval of
      other beans. Sometimes this capability is useful; however, in general you
      should avoid it, because it couples the code to Spring and does not follow
      the Inversion of Control style, where collaborators are provided to beans
      as properties. Other methods of the ApplicationContext provide access to
      file resources, publishing application events, and accessing a
      MessageSource. These additional features are described in <a class="xref" href="beans.html#context-introduction" title="4.14&nbsp;Additional Capabilities of the ApplicationContext">Section&nbsp;4.14, &#8220;Additional Capabilities of the
    ApplicationContext&#8221;</a></p><p>As of Spring 2.5, autowiring is another alternative to obtain
      reference to the <code class="interfacename">ApplicationContext</code>. The
      "traditional" <code class="literal">constructor</code> and <code class="literal">byType</code>
      autowiring modes (as described in <a class="xref" href="beans.html#beans-factory-autowire" title="4.4.5&nbsp;Autowiring collaborators">Section&nbsp;4.4.5, &#8220;Autowiring collaborators&#8221;</a>) can provide a dependency of type
      <code class="interfacename">ApplicationContext</code> for a constructor
      argument or setter method parameter, respectively. For more flexibility,
      including the ability to autowire fields and multiple parameter methods,
      use the new annotation-based autowiring features. If you do, the
      <code class="interfacename">ApplicationFactory</code> is autowired into a
      field, constructor argument, or method parameter that is expecting the
      <code class="interfacename">BeanFactory</code> type if the field, constructor,
      or method in question carries the
      <code class="interfacename">@Autowired</code> annotation. For more
      information, see <a class="xref" href="beans.html#beans-autowired-annotation" title="4.9.2&nbsp;@Autowired and @Inject">Section&nbsp;4.9.2, &#8220;@Autowired and @Inject&#8221;</a>.</p><p>When an ApplicationContext creates a class that implements the
      <code class="interfacename">org.springframework.beans.factory.BeanNameAware</code>
      interface, the class is provided with a reference to the name defined in
      its associated object definition.</p><pre class="programlisting"><span class="hl-keyword">public</span> <span class="hl-keyword">interface</span> BeanNameAware {

  <span class="hl-keyword">void</span> setBeanName(string name) <span class="hl-keyword">throws</span> BeansException;
}</pre><p>The callback is invoked after population of normal bean properties but
      before an initialization callback such as
      <code class="interfacename">InitializingBean</code>s
      <span class="emphasis"><em>afterPropertiesSet</em></span> or a custom init-method.</p></div><div class="section" lang="en"><div class="titlepage"><div><div><h3 class="title"><a name="aware-list"></a>4.6.3&nbsp;Other <code class="interfacename">Aware</code> interfaces</h3></div></div></div><p>Besides <code class="interfacename">ApplicationContextAware</code> and
      <code class="interfacename">BeanNameAware</code> discussed above, Spring
      offers a range of
      <span class="emphasis"><em><code class="interfacename">Aware</code></em></span> interfaces that
      allow beans to indicate to the container that they require a certain
      <span class="emphasis"><em>infrastructure</em></span> dependency. The most important
      <code class="interfacename">Aware</code> interfaces are summarized below - as
      a general rule, the name is a good indication of the dependency
      type:</p><div class="table"><a name="beans-factory-nature-aware-list"></a><p class="title"><b>Table&nbsp;4.4.&nbsp;<code class="interfacename">Aware</code> interfaces</b></p><div class="table-contents"><table summary="Aware interfaces" width="100%" style="border-collapse: collapse;border-top: 1.0pt solid ; border-bottom: 1.0pt solid ; border-left: 1.0pt solid ; border-right: 1.0pt solid ; "><colgroup><col align="left"><col><col></colgroup><thead><tr><th style="border-right: 1.0pt solid ; border-bottom: 1.0pt solid ; " align="left">Name</th><th style="border-right: 1.0pt solid ; border-bottom: 1.0pt solid ; ">Injected Dependency</th><th style="border-bottom: 1.0pt solid ; ">Explained in...</th></tr></thead><tbody><tr><td style="border-right: 1.0pt solid ; border-bottom: 1.0pt solid ; " align="left"><p><code class="classname">ApplicationContextAware</code></p></td><td style="border-right: 1.0pt solid ; border-bottom: 1.0pt solid ; "><p>Declaring
              <code class="interfacename">ApplicationContext</code></p></td><td style="border-bottom: 1.0pt solid ; "><p><a class="xref" href="beans.html#beans-factory-aware" title="4.6.2&nbsp;ApplicationContextAware and BeanNameAware">Section&nbsp;4.6.2, &#8220;ApplicationContextAware and
      BeanNameAware&#8221;</a></p></td></tr><tr><td style="border-right: 1.0pt solid ; border-bottom: 1.0pt solid ; " align="left"><p><code class="classname">ApplicationEventPublisherAware</code></p></td><td style="border-right: 1.0pt solid ; border-bottom: 1.0pt solid ; "><p>Event publisher of the enclosing
              <code class="interfacename">ApplicationContext</code></p></td><td style="border-bottom: 1.0pt solid ; "><p><a class="xref" href="beans.html#context-introduction" title="4.14&nbsp;Additional Capabilities of the ApplicationContext">Section&nbsp;4.14, &#8220;Additional Capabilities of the
    ApplicationContext&#8221;</a></p></td></tr><tr><td style="border-right: 1.0pt solid ; border-bottom: 1.0pt solid ; " align="left"><p><code class="classname">BeanClassLoaderAware</code></p></td><td style="border-right: 1.0pt solid ; border-bottom: 1.0pt solid ; "><p>Class loader used to load the bean
              classes.</p></td><td style="border-bottom: 1.0pt solid ; "><p><a class="xref" href="beans.html#beans-factory-class" title="4.3.2&nbsp;Instantiating beans">Section&nbsp;4.3.2, &#8220;Instantiating beans&#8221;</a></p></td></tr><tr><td style="border-right: 1.0pt solid ; border-bottom: 1.0pt solid ; " align="left"><p><code class="classname">BeanFactoryAware</code></p></td><td style="border-right: 1.0pt solid ; border-bottom: 1.0pt solid ; "><p>Declaring
              <code class="interfacename">BeanFactory</code></p></td><td style="border-bottom: 1.0pt solid ; "><p><a class="xref" href="beans.html#beans-factory-aware" title="4.6.2&nbsp;ApplicationContextAware and BeanNameAware">Section&nbsp;4.6.2, &#8220;ApplicationContextAware and
      BeanNameAware&#8221;</a></p></td></tr><tr><td style="border-right: 1.0pt solid ; border-bottom: 1.0pt solid ; " align="left"><p><code class="classname">BeanNameAware</code></p></td><td style="border-right: 1.0pt solid ; border-bottom: 1.0pt solid ; "><p>Name of the declaring bean</p></td><td style="border-bottom: 1.0pt solid ; "><p><a class="xref" href="beans.html#beans-factory-aware" title="4.6.2&nbsp;ApplicationContextAware and BeanNameAware">Section&nbsp;4.6.2, &#8220;ApplicationContextAware and
      BeanNameAware&#8221;</a></p></td></tr><tr><td style="border-right: 1.0pt solid ; border-bottom: 1.0pt solid ; " align="left"><p><code class="classname">BootstrapContextAware</code></p></td><td style="border-right: 1.0pt solid ; border-bottom: 1.0pt solid ; "><p>Resource adapter
              <code class="interfacename">BootstrapContext</code> the container runs
              in. Typically available only in JCA aware
              <code class="interfacename">ApplicationContext</code>s</p></td><td style="border-bottom: 1.0pt solid ; "><p><a class="xref" href="cci.html" title="24.&nbsp;JCA CCI">Chapter&nbsp;24, <i>JCA CCI</i></a></p></td></tr><tr><td style="border-right: 1.0pt solid ; border-bottom: 1.0pt solid ; " align="left"><p><code class="classname">LoadTimeWeaverAware</code></p></td><td style="border-right: 1.0pt solid ; border-bottom: 1.0pt solid ; "><p>Defined <span class="emphasis"><em>weaver</em></span> for processing
              class definition at load time</p></td><td style="border-bottom: 1.0pt solid ; "><p><a class="xref" href="aop.html#aop-aj-ltw" title="8.8.4&nbsp;Load-time weaving with AspectJ in the Spring Framework">Section&nbsp;8.8.4, &#8220;Load-time weaving with AspectJ in the Spring Framework&#8221;</a></p></td></tr><tr><td style="border-right: 1.0pt solid ; border-bottom: 1.0pt solid ; " align="left"><p><code class="classname">MessageSourceAware</code></p></td><td style="border-right: 1.0pt solid ; border-bottom: 1.0pt solid ; "><p>Configured strategy for resolving messages (with
              support for parametrization and
              internationalization)</p></td><td style="border-bottom: 1.0pt solid ; "><p><a class="xref" href="beans.html#context-introduction" title="4.14&nbsp;Additional Capabilities of the ApplicationContext">Section&nbsp;4.14, &#8220;Additional Capabilities of the
    ApplicationContext&#8221;</a></p></td></tr><tr><td style="border-right: 1.0pt solid ; border-bottom: 1.0pt solid ; " align="left"><p><code class="classname">NotificationPublisherAware</code></p></td><td style="border-right: 1.0pt solid ; border-bottom: 1.0pt solid ; "><p>Spring JMX notification publisher</p></td><td style="border-bottom: 1.0pt solid ; "><p><a class="xref" href="jmx.html#jmx-notifications" title="23.7&nbsp;Notifications">Section&nbsp;23.7, &#8220;Notifications&#8221;</a></p></td></tr><tr><td style="border-right: 1.0pt solid ; border-bottom: 1.0pt solid ; " align="left"><p><code class="classname">PortletConfigAware</code></p></td><td style="border-right: 1.0pt solid ; border-bottom: 1.0pt solid ; "><p>Current <code class="interfacename">PortletConfig</code>
              the container runs in. Valid only in a web-aware Spring
              <code class="interfacename">ApplicationContext</code></p></td><td style="border-bottom: 1.0pt solid ; "><p><a class="xref" href="portlet.html" title="19.&nbsp;Portlet MVC Framework">Chapter&nbsp;19, <i>Portlet MVC Framework</i></a></p></td></tr><tr><td style="border-right: 1.0pt solid ; border-bottom: 1.0pt solid ; " align="left"><p><code class="classname">PortletContextAware</code></p></td><td style="border-right: 1.0pt solid ; border-bottom: 1.0pt solid ; "><p>Current <code class="interfacename">PortletContext</code>
              the container runs in. Valid only in a web-aware Spring
              <code class="interfacename">ApplicationContext</code></p></td><td style="border-bottom: 1.0pt solid ; "><p><a class="xref" href="portlet.html" title="19.&nbsp;Portlet MVC Framework">Chapter&nbsp;19, <i>Portlet MVC Framework</i></a></p></td></tr><tr><td style="border-right: 1.0pt solid ; border-bottom: 1.0pt solid ; " align="left"><p><code class="classname">ResourceLoaderAware</code></p></td><td style="border-right: 1.0pt solid ; border-bottom: 1.0pt solid ; "><p>Configured loader for low-level access to
              resources</p></td><td style="border-bottom: 1.0pt solid ; "><p><a class="xref" href="resources.html" title="5.&nbsp;Resources">Chapter&nbsp;5, <i>Resources</i></a></p></td></tr><tr><td style="border-right: 1.0pt solid ; border-bottom: 1.0pt solid ; " align="left"><p><code class="classname">ServletConfigAware</code></p></td><td style="border-right: 1.0pt solid ; border-bottom: 1.0pt solid ; "><p>Current <code class="interfacename">ServletConfig</code>
              the container runs in. Valid only in a web-aware Spring
              <code class="interfacename">ApplicationContext</code></p></td><td style="border-bottom: 1.0pt solid ; "><p><a class="xref" href="mvc.html" title="16.&nbsp;Web MVC framework">Chapter&nbsp;16, <i>Web MVC framework</i></a></p></td></tr><tr><td style="border-right: 1.0pt solid ; " align="left"><p><code class="classname">ServletContextAware</code></p></td><td style="border-right: 1.0pt solid ; "><p>Current <code class="interfacename">ServletContext</code>
              the container runs in. Valid only in a web-aware Spring
              <code class="interfacename">ApplicationContext</code></p></td><td style=""><p><a class="xref" href="mvc.html" title="16.&nbsp;Web MVC framework">Chapter&nbsp;16, <i>Web MVC framework</i></a></p></td></tr></tbody></table></div></div><br class="table-break"><p>Note again that usage of these interfaces ties your code to the Spring
      API and does not follow the Inversion of Control style. As such, they are
      recommended for infrastructure beans that require programmatic access to
      the container.</p></div></div><div class="section" lang="en"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="beans-child-bean-definitions"></a>4.7&nbsp;Bean definition inheritance</h2></div></div></div><p>A bean definition can contain a lot of configuration information,
      including constructor arguments, property values, and container-specific
      information such as initialization method, static factory method name, and
      so on. A child bean definition inherits configuration data from a parent
      definition. The child definition can override some values, or add others,
      as needed. Using parent and child bean definitions can save a lot of
      typing. Effectively, this is a form of templating.</p><p>If you work with an <code class="interfacename">ApplicationContext</code>
      interface programmatically, child bean definitions are represented by the
      <code class="classname">ChildBeanDefinition</code> class. Most users do not work
      with them on this level, instead configuring bean definitions
      declaratively in something like the
      <code class="classname">ClassPathXmlApplicationContext</code>. When you use
      XML-based configuration metadata, you indicate a child bean definition by
      using the <code class="literal">parent</code> attribute, specifying the parent bean
      as the value of this attribute.</p><pre class="programlisting">&lt;<span class="hl-tag">bean</span> <span class="hl-attribute">id</span>=<span class="hl-value">"inheritedTestBean"</span> <span class="hl-attribute">abstract</span>=<span class="hl-value">"true"</span>
    <span class="hl-attribute">class</span>=<span class="hl-value">"org.springframework.beans.TestBean"</span>&gt;
  &lt;<span class="hl-tag">property</span> <span class="hl-attribute">name</span>=<span class="hl-value">"name"</span> <span class="hl-attribute">value</span>=<span class="hl-value">"parent"</span>/&gt;
  &lt;<span class="hl-tag">property</span> <span class="hl-attribute">name</span>=<span class="hl-value">"age"</span> <span class="hl-attribute">value</span>=<span class="hl-value">"1"</span>/&gt;
&lt;<span class="hl-tag">/bean</span>&gt;

&lt;<span class="hl-tag">bean</span> <span class="hl-attribute">id</span>=<span class="hl-value">"inheritsWithDifferentClass"</span>
      <span class="hl-attribute">class</span>=<span class="hl-value">"org.springframework.beans.DerivedTestBean"</span>
      <span class="hl-attribute">parent</span>=<span class="hl-value">"inheritedTestBean"</span> <span class="hl-attribute">init-method</span>=<span class="hl-value">"initialize"</span>&gt;

  &lt;<span class="hl-tag">property</span> <span class="hl-attribute">name</span>=<span class="hl-value">"name"</span> <span class="hl-attribute">value</span>=<span class="hl-value">"override"</span>/&gt;
  &lt;<span class="hl-comment">!-- the age property value of 1 will be inherited from  parent --</span>&gt;

&lt;<span class="hl-tag">/bean</span>&gt;</pre><p>A child bean definition uses the bean class from the parent definition
      if none is specified, but can also override it. In the latter case, the
      child bean class must be compatible with the parent, that is, it must
      accept the parent's property values.</p><p>A child bean definition inherits constructor argument values, property
      values, and method overrides from the parent, with the option to add new
      values. Any initialization method, destroy method, and/or
      <code class="literal">static</code> factory method settings that you specify will
      override the corresponding parent settings.</p><p>The remaining settings are <span class="emphasis"><em>always</em></span> taken from the
      child definition: <span class="emphasis"><em>depends on</em></span>, <span class="emphasis"><em>autowire
      mode</em></span>, <span class="emphasis"><em>dependency check</em></span>,
      <span class="emphasis"><em>singleton</em></span>, <span class="emphasis"><em>scope</em></span>, <span class="emphasis"><em>lazy
      init</em></span>.</p><p>The preceding example explicitly marks the parent bean definition as
      abstract by using the <code class="literal">abstract</code> attribute. If the parent
      definition does not specify a class, explicitly marking the parent bean
      definition as <code class="literal">abstract</code> is required, as follows:</p><pre class="programlisting">&lt;<span class="hl-tag">bean</span> <span class="hl-attribute">id</span>=<span class="hl-value">"inheritedTestBeanWithoutClass"</span> <span class="hl-attribute">abstract</span>=<span class="hl-value">"true"</span>&gt;
    &lt;<span class="hl-tag">property</span> <span class="hl-attribute">name</span>=<span class="hl-value">"name"</span> <span class="hl-attribute">value</span>=<span class="hl-value">"parent"</span>/&gt;
    &lt;<span class="hl-tag">property</span> <span class="hl-attribute">name</span>=<span class="hl-value">"age"</span> <span class="hl-attribute">value</span>=<span class="hl-value">"1"</span>/&gt;
&lt;<span class="hl-tag">/bean</span>&gt;

&lt;<span class="hl-tag">bean</span> <span class="hl-attribute">id</span>=<span class="hl-value">"inheritsWithClass"</span> <span class="hl-attribute">class</span>=<span class="hl-value">"org.springframework.beans.DerivedTestBean"</span>
    <span class="hl-attribute">parent</span>=<span class="hl-value">"inheritedTestBeanWithoutClass"</span> <span class="hl-attribute">init-method</span>=<span class="hl-value">"initialize"</span>&gt;
  &lt;<span class="hl-tag">property</span> <span class="hl-attribute">name</span>=<span class="hl-value">"name"</span> <span class="hl-attribute">value</span>=<span class="hl-value">"override"</span>/&gt;
  &lt;<span class="hl-comment">!-- age will inherit the value of 1 from the parent bean definition--</span>&gt;
&lt;<span class="hl-tag">/bean</span>&gt;</pre><p>The parent bean cannot be instantiated on its own because it is
      incomplete, and it is also explicitly marked as
      <code class="literal">abstract</code>. When a definition is
      <code class="literal">abstract</code> like this, it is usable only as a pure
      template bean definition that serves as a parent definition for child
      definitions. Trying to use such an <code class="literal">abstract</code> parent bean
      on its own, by referring to it as a ref property of another bean or doing
      an explicit <code class="methodname">getBean()</code> call with the parent bean
      id, returns an error. Similarly, the container's internal
      <code class="methodname">preInstantiateSingletons()</code> method ignores bean
      definitions that are defined as abstract.</p><div class="note" style="margin-left: 0.5in; margin-right: 0.5in;"><table border="0" summary="Note"><tr><td rowspan="2" align="center" valign="top" width="25"><img alt="[Note]" src="images/note.gif"></td><th align="left">Note</th></tr><tr><td align="left" valign="top"><p><code class="literal">ApplicationContext</code> pre-instantiates all
        singletons by default. Therefore, it is important (at least for
        singleton beans) that if you have a (parent) bean definition which you
        intend to use only as a template, and this definition specifies a class,
        you must make sure to set the <span class="emphasis"><em>abstract</em></span> attribute to
        <span class="emphasis"><em>true</em></span>, otherwise the application context will
        actually (attempt to) pre-instantiate the <code class="literal">abstract</code>
        bean.</p></td></tr></table></div></div><div class="section" lang="en"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="beans-factory-extension"></a>4.8&nbsp;Container Extension Points</h2></div></div></div><p>Typically, an application developer does not need to subclass
    <code class="interfacename">ApplicationContext</code> implementation classes.
    Instead, the Spring IoC container can be extended by plugging in
    implementations of special integration interfaces. The next few sections
    describe these integration interfaces.</p><div class="section" lang="en"><div class="titlepage"><div><div><h3 class="title"><a name="beans-factory-extension-bpp"></a>4.8.1&nbsp;Customizing beans using a
      <code class="interfacename">BeanPostProcessor</code></h3></div></div></div><p>The <code class="interfacename">BeanPostProcessor</code> interface defines
      <em class="firstterm">callback methods</em> that you can implement to provide
      your own (or override the container's default) instantiation logic,
      dependency-resolution logic, and so forth. If you want to implement some
      custom logic after the Spring container finishes instantiating,
      configuring, and initializing a bean, you can plug in one or
      more <code class="interfacename">BeanPostProcessor</code>
      implementations.</p><p>You can configure multiple <code class="literal">BeanPostProcessor</code>
      instances, and you can control the order in which these
      <code class="literal">BeanPostProcessor</code>s execute by setting the
      <code class="literal">order</code> property. You can set this property only if the
      <code class="interfacename">BeanPostProcessor</code> implements the
      <code class="interfacename">Ordered</code> interface; if you write your own
      <code class="interfacename">BeanPostProcessor</code> you should consider
      implementing the <code class="interfacename">Ordered</code> interface too. For
      further details, consult the Javadoc for the
      <code class="interfacename">BeanPostProcessor</code> and
      <code class="interfacename">Ordered</code> interfaces.</p><div class="note" style="margin-left: 0.5in; margin-right: 0.5in;"><table border="0" summary="Note"><tr><td rowspan="2" align="center" valign="top" width="25"><img alt="[Note]" src="images/note.gif"></td><th align="left">Note</th></tr><tr><td align="left" valign="top"><p><code class="literal">BeanPostProcessor</code>s operate on bean (or object)
        <span class="emphasis"><em>instances</em></span>; that is to say, the Spring IoC container
        instantiates a bean instance and <span class="emphasis"><em>then</em></span>
        <code class="literal">BeanPostProcessor</code>s do their work.</p><p><code class="literal">BeanPostProcessor</code>s are scoped
        <span class="emphasis"><em>per-container</em></span>. This is only relevant if you are
        using container hierarchies. If you define a
        <code class="interfacename">BeanPostProcessor</code> in one container, it
        will <span class="emphasis"><em>only</em></span> post-process the beans in that
        container. In other words, beans that are defined in one container are not
        post-processed by a <code class="literal">BeanPostProcessor</code> defined in another
        container, even if both containers are part of the same hierarchy.</p><p>To change the actual bean definition (i.e., the
        <span class="emphasis"><em>blueprint</em></span> that defines the bean), you instead need to use a
        <code class="interfacename">BeanFactoryPostProcessor</code> as described
        in <a class="xref" href="beans.html#beans-factory-extension-factory-postprocessors" title="4.8.2&nbsp;Customizing configuration metadata with a BeanFactoryPostProcessor">Section&nbsp;4.8.2, &#8220;Customizing configuration metadata with a
      BeanFactoryPostProcessor&#8221;</a>.</p></td></tr></table></div><p>The
      <code class="interfacename">org.springframework.beans.factory.config.BeanPostProcessor</code>
      interface consists of exactly two callback methods. When such a class is
      registered as a post-processor with the container, for each bean instance
      that is created by the container, the post-processor gets a callback from
      the container both <span class="emphasis"><em>before</em></span> container initialization
      methods (such as InitializingBean's <span class="emphasis"><em>afterPropertiesSet()</em></span>
      and any declared init method) are called as well as <span class="emphasis"><em>after</em></span>
      any bean initialization callbacks. The post-processor can take
      any action with the bean instance, including ignoring the callback
      completely. A bean post-processor typically checks for callback
      interfaces or may wrap a bean with a proxy. Some Spring AOP
      infrastructure classes are implemented as bean post-processors in order
      to provide proxy-wrapping logic.</p><p>An <code class="interfacename">ApplicationContext</code>
      <span class="emphasis"><em>automatically detects</em></span> any beans that are defined in
      the configuration metadata which implement the
      <code class="interfacename">BeanPostProcessor</code> interface. The
      <code class="interfacename">ApplicationContext</code> registers these beans as
      post-processors so that they can be called later upon bean creation.
      Bean post-processors can be deployed in the container just like any other
      beans.</p><div class="note" style="margin-left: 0.5in; margin-right: 0.5in;"><table border="0" summary="Note: BeanPostProcessors and AOP&#xA;        auto-proxying"><tr><td rowspan="2" align="center" valign="top" width="25"><img alt="[Note]" src="images/note.gif"></td><th align="left">BeanPostProcessors and AOP
        auto-proxying</th></tr><tr><td align="left" valign="top"><p>Classes that implement the
        <code class="interfacename">BeanPostProcessor</code> interface are
        <span class="emphasis"><em>special</em></span> and are treated differently by the
        container. All <code class="interfacename">BeanPostProcessors</code>
        <span class="emphasis"><em>and beans that they reference directly</em></span> are
        instantiated on startup, as part of the special startup phase of the
        <code class="interfacename">ApplicationContext</code>. Next, all
        <code class="interfacename">BeanPostProcessors</code> are registered in a
        sorted fashion and applied to all further beans in the container.
        Because AOP auto-proxying is implemented as a
        <code class="interfacename">BeanPostProcessor</code> itself, neither
        <code class="interfacename">BeanPostProcessors</code> nor the beans they reference
        directly are eligible for auto-proxying, and thus do not have aspects woven
        into them.</p><p>For any such bean, you should see an informational log message:
        &#8220;<span class="quote"><span class="emphasis"><em>Bean foo is not eligible for getting processed by all
        BeanPostProcessor interfaces (for example: not eligible for
        auto-proxying)</em></span></span>&#8221;.</p></td></tr></table></div><p>The following examples show how to write, register, and use
      <code class="literal">BeanPostProcessors</code> in an
      <code class="interfacename">ApplicationContext</code>.</p><div class="section" lang="en"><div class="titlepage"><div><div><h4 class="title"><a name="beans-factory-extension-bpp-examples-hw"></a>4.8.1.1&nbsp;Example: Hello World,
        <code class="interfacename">BeanPostProcessor</code>-style</h4></div></div></div><p>This first example illustrates basic usage. The example shows a
        custom <code class="interfacename">BeanPostProcessor</code> implementation
        that invokes the <code class="methodname">toString()</code> method of each bean
        as it is created by the container and prints the resulting string to the
        system console.</p><p>Find below the custom
        <code class="interfacename">BeanPostProcessor</code> implementation class
        definition:</p><pre class="programlisting"><span class="hl-keyword">package</span> scripting;

<span class="hl-keyword">import</span> org.springframework.beans.factory.config.BeanPostProcessor;
<span class="hl-keyword">import</span> org.springframework.beans.BeansException;

<span class="hl-keyword">public</span> <span class="hl-keyword">class</span> InstantiationTracingBeanPostProcessor <span class="hl-keyword">implements</span> BeanPostProcessor {

  <span class="hl-comment">// simply return the instantiated bean as-is</span>
  <span class="hl-keyword">public</span> Object postProcessBeforeInitialization(Object bean, String beanName)
                                                                     <span class="hl-keyword">throws</span> BeansException {
      <span class="hl-keyword">return</span> bean; <span class="hl-comment">// we could potentially return any object reference here...</span>
  }

  <span class="hl-keyword">public</span> Object postProcessAfterInitialization(Object bean, String beanName)
                                                                     <span class="hl-keyword">throws</span> BeansException {
      System.out.println(<span class="hl-string">"Bean '"</span> + beanName + <span class="hl-string">"' created : "</span> + bean.toString());
      <span class="hl-keyword">return</span> bean;
  }
}</pre><pre class="programlisting">&lt;<span class="hl-tag">?xml version="1.0" encoding="UTF-8"?</span>&gt;
&lt;<span class="hl-tag">beans</span> <span class="hl-attribute">xmlns</span>=<span class="hl-value">"http://www.springframework.org/schema/beans"</span>
     <span class="hl-attribute">xmlns:xsi</span>=<span class="hl-value">"http://www.w3.org/2001/XMLSchema-instance"</span>
     <span class="hl-attribute">xmlns:lang</span>=<span class="hl-value">"http://www.springframework.org/schema/lang"</span>
     <span class="hl-attribute">xsi:schemaLocation</span>=<span class="hl-value">"http://www.springframework.org/schema/beans
         http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
         http://www.springframework.org/schema/lang
         http://www.springframework.org/schema/lang/spring-lang-3.0.xsd"</span>&gt;

  &lt;<span class="hl-tag">lang:groovy</span> <span class="hl-attribute">id</span>=<span class="hl-value">"messenger"</span>
        <span class="hl-attribute">script-source</span>=<span class="hl-value">"classpath:org/springframework/scripting/groovy/Messenger.groovy"</span>&gt;
      &lt;<span class="hl-tag">lang:property</span> <span class="hl-attribute">name</span>=<span class="hl-value">"message"</span> <span class="hl-attribute">value</span>=<span class="hl-value">"Fiona Apple Is Just So Dreamy."</span>/&gt;
  &lt;<span class="hl-tag">/lang:groovy</span>&gt;

  &lt;<span class="hl-comment">!--
      when the above bean (messenger) is instantiated, this custom
      BeanPostProcessor implementation will output the fact to the system console
   --</span>&gt;
  &lt;<span class="hl-tag">bean</span> <span class="hl-attribute">class</span>=<span class="hl-value">"scripting.InstantiationTracingBeanPostProcessor"</span>/&gt;

&lt;<span class="hl-tag">/beans</span>&gt;</pre><p>Notice how the
        <code class="classname">InstantiationTracingBeanPostProcessor</code> is simply
        defined. It does not even have a name, and because it is a bean it can
        be dependency-injected just like any other bean. (The preceding
        configuration also defines a bean that is backed by a Groovy script. The
        Spring 2.0 dynamic language support is detailed in the chapter entitled
        <a class="xref" href="dynamic-language.html" title="27.&nbsp;Dynamic language support">Chapter&nbsp;27, <i>Dynamic language support</i></a>.)</p><p>The following simple Java application executes the preceding code and
        configuration:</p><pre class="programlisting"><span class="hl-keyword">import</span> org.springframework.context.ApplicationContext;
<span class="hl-keyword">import</span> org.springframework.context.support.ClassPathXmlApplicationContext;
<span class="hl-keyword">import</span> org.springframework.scripting.Messenger;

<span class="hl-keyword">public</span> <span class="hl-keyword">final</span> <span class="hl-keyword">class</span> Boot {

  <span class="hl-keyword">public</span> <span class="hl-keyword">static</span> <span class="hl-keyword">void</span> main(<span class="hl-keyword">final</span> String[] args) <span class="hl-keyword">throws</span> Exception {
      ApplicationContext ctx = <span class="hl-keyword">new</span> ClassPathXmlApplicationContext(<span class="hl-string">"scripting/beans.xml"</span>);
      Messenger messenger = (Messenger) ctx.getBean(<span class="hl-string">"messenger"</span>);
      System.out.println(messenger);
  }
}</pre><p>The output of the preceding application resembles the
        following:</p><pre class="programlisting">Bean 'messenger' created : org.springframework.scripting.groovy.GroovyMessenger@272961
org.springframework.scripting.groovy.GroovyMessenger@272961</pre></div><div class="section" lang="en"><div class="titlepage"><div><div><h4 class="title"><a name="beans-factory-extension-bpp-examples-rabpp"></a>4.8.1.2&nbsp;Example: The
        <code class="classname">RequiredAnnotationBeanPostProcessor</code></h4></div></div></div><p>Using callback interfaces or annotations in conjunction with a
        custom <code class="interfacename">BeanPostProcessor</code> implementation
        is a common means of extending the Spring IoC container. An example is
        Spring's <code class="classname">RequiredAnnotationBeanPostProcessor</code> &#8212; a
        <code class="interfacename">BeanPostProcessor</code> implementation that
        ships with the Spring distribution which ensures that JavaBean
        properties on beans that are marked with an (arbitrary) annotation are
        actually (configured to be) dependency-injected with a value.</p></div></div><div class="section" lang="en"><div class="titlepage"><div><div><h3 class="title"><a name="beans-factory-extension-factory-postprocessors"></a>4.8.2&nbsp;Customizing configuration metadata with a
      <code class="interfacename">BeanFactoryPostProcessor</code></h3></div></div></div><p>The next extension point that we will look at is the
      <code class="interfacename">org.springframework.beans.factory.config.BeanFactoryPostProcessor</code>.
      The semantics of this interface are similar to those of the
      <code class="interfacename">BeanPostProcessor</code>, with one major
      difference: <code class="literal">BeanFactoryPostProcessor</code>s operate on the
      <span class="emphasis"><em>bean configuration metadata</em></span>; that is, the Spring IoC
      container allows <code class="literal">BeanFactoryPostProcessors</code> to read the
      configuration metadata and potentially change it
      <span class="emphasis"><em>before</em></span> the container instantiates any beans other
      than <code class="literal">BeanFactoryPostProcessors</code>.</p><p>You can configure multiple
      <code class="literal">BeanFactoryPostProcessors</code>, and you can control the order in
      which these <code class="literal">BeanFactoryPostProcessors</code> execute by
      setting the <code class="literal">order</code> property. However, you can only set
      this property if the
      <code class="interfacename">BeanFactoryPostProcessor</code> implements the
      <code class="interfacename">Ordered</code> interface. If you write your own
      <code class="interfacename">BeanFactoryPostProcessor</code>, you should
      consider implementing the <code class="interfacename">Ordered</code> interface
      too. Consult the Javadoc for the
      <code class="interfacename">BeanFactoryPostProcessor</code> and
      <code class="interfacename">Ordered</code> interfaces for more details.</p><div class="note" style="margin-left: 0.5in; margin-right: 0.5in;"><table border="0" summary="Note"><tr><td rowspan="2" align="center" valign="top" width="25"><img alt="[Note]" src="images/note.gif"></td><th align="left">Note</th></tr><tr><td align="left" valign="top"><p>If you want to change the actual bean <span class="emphasis"><em>instances</em></span>
        (i.e., the objects that are created from the configuration metadata), then you
        instead need to use a <code class="interfacename">BeanPostProcessor</code>
        (described above in <a class="xref" href="beans.html#beans-factory-extension-bpp" title="4.8.1&nbsp;Customizing beans using a BeanPostProcessor">Section&nbsp;4.8.1, &#8220;Customizing beans using a
      BeanPostProcessor&#8221;</a>). While
        it is technically possible to work with bean instances within a
        <code class="interfacename">BeanFactoryPostProcessor</code> (e.g., using
        <code class="methodname">BeanFactory.getBean()</code>), doing so causes
        premature bean instantiation, violating the standard container lifecycle.
        This may cause negative side effects such as bypassing bean post
        processing.</p><p>Also, <code class="literal">BeanFactoryPostProcessors</code> are scoped
        <span class="emphasis"><em>per-container</em></span>. This is only relevant if you are
        using container hierarchies. If you define a
        <code class="interfacename">BeanFactoryPostProcessor</code> in one
        container, it will <span class="emphasis"><em>only</em></span> be applied to the bean
        definitions in that container. Bean definitions in one container
        will not be post-processed by
        <code class="literal">BeanFactoryPostProcessors</code> in another container, even
        if both containers are part of the same hierarchy.</p></td></tr></table></div><p>A bean factory post-processor is executed automatically when it is
      declared inside an <code class="interfacename">ApplicationContext</code>,
      in order to apply changes to the configuration metadata that define the
      container. Spring includes a number of predefined bean factory
      post-processors, such as <code class="classname">PropertyOverrideConfigurer</code>
      and <code class="classname">PropertyPlaceholderConfigurer</code>. A custom
      <code class="interfacename">BeanFactoryPostProcessor</code> can also be used,
      for example, to register custom property editors.</p><a name="beans-factory-autodetect-beanfactorypostprocessors"></a><p>An <code class="interfacename">ApplicationContext</code> automatically
      detects any beans that are deployed into it that implement the
      <code class="interfacename">BeanFactoryPostProcessor</code> interface. It
      uses these beans as bean factory post-processors, at the
      appropriate time. You can deploy these post-processor beans as you
      would any other bean.</p><div class="note" style="margin-left: 0.5in; margin-right: 0.5in;"><table border="0" summary="Note"><tr><td rowspan="2" align="center" valign="top" width="25"><img alt="[Note]" src="images/note.gif"></td><th align="left">Note</th></tr><tr><td align="left" valign="top"><p>As with <code class="interfacename">BeanPostProcessor</code>s, you typically
        do not want to configure <code class="interfacename">BeanFactoryPostProcessor</code>s
        for lazy initialization. If no other bean references a
        <code class="interfacename">Bean(Factory)PostProcessor</code>,
        that post-processor will not get instantiated at all. Thus, marking it for
        lazy initialization will be ignored, and the 
        <code class="interfacename">Bean(Factory)PostProcessor</code> will be
        instantiated eagerly even if you set the <code class="literal">default-lazy-init</code>
        attribute to <code class="literal">true</code> on the declaration of your
        <code class="code">&lt;beans /&gt;</code> element.</p></td></tr></table></div><div class="section" lang="en"><div class="titlepage"><div><div><h4 class="title"><a name="beans-factory-placeholderconfigurer"></a>4.8.2.1&nbsp;Example: the
        <code class="interfacename">PropertyPlaceholderConfigurer</code></h4></div></div></div><p>You use the
        <code class="interfacename">PropertyPlaceholderConfigurer</code> to
        externalize property values from a bean definition in a separate
        file using the standard Java <code class="classname">Properties</code> format.
        Doing so enables the person deploying an application to customize
        environment-specific properties such as database URLs and passwords,
        without the complexity or risk of modifying the main XML definition file
        or files for the container.</p><p>Consider the following XML-based configuration metadata fragment,
        where a <code class="interfacename">DataSource</code> with placeholder
        values is defined. The example shows properties configured from an
        external <code class="classname">Properties</code> file. At runtime, a
        <code class="classname">PropertyPlaceholderConfigurer</code> is applied to the
        metadata that will replace some properties of the DataSource. The values
        to replace are specified as <span class="emphasis"><em>placeholders</em></span> of the form
        ${property-name} which follows the Ant / log4j / JSP EL style.</p><pre class="programlisting">&lt;<span class="hl-tag">bean</span> <span class="hl-attribute">class</span>=<span class="hl-value">"org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"</span>&gt;
  &lt;<span class="hl-tag">property</span> <span class="hl-attribute">name</span>=<span class="hl-value">"locations"</span> <span class="hl-attribute">value</span>=<span class="hl-value">"classpath:com/foo/jdbc.properties"</span>/&gt;
&lt;<span class="hl-tag">/bean</span>&gt;

&lt;<span class="hl-tag">bean</span> <span class="hl-attribute">id</span>=<span class="hl-value">"dataSource"</span> <span class="hl-attribute">destroy-method</span>=<span class="hl-value">"close"</span>
    <span class="hl-attribute">class</span>=<span class="hl-value">"org.apache.commons.dbcp.BasicDataSource"</span>&gt;
  &lt;<span class="hl-tag">property</span> <span class="hl-attribute">name</span>=<span class="hl-value">"driverClassName"</span> <span class="hl-attribute">value</span>=<span class="hl-value">"${jdbc.driverClassName}"</span>/&gt;
  &lt;<span class="hl-tag">property</span> <span class="hl-attribute">name</span>=<span class="hl-value">"url"</span> <span class="hl-attribute">value</span>=<span class="hl-value">"${jdbc.url}"</span>/&gt;
  &lt;<span class="hl-tag">property</span> <span class="hl-attribute">name</span>=<span class="hl-value">"username"</span> <span class="hl-attribute">value</span>=<span class="hl-value">"${jdbc.username}"</span>/&gt;
  &lt;<span class="hl-tag">property</span> <span class="hl-attribute">name</span>=<span class="hl-value">"password"</span> <span class="hl-attribute">value</span>=<span class="hl-value">"${jdbc.password}"</span>/&gt;
&lt;<span class="hl-tag">/bean</span>&gt;</pre><p>The actual values come from another file in the standard Java
        <code class="classname">Properties</code> format:</p><pre class="programlisting">jdbc.driverClassName=org.hsqldb.jdbcDriver
jdbc.url=jdbc:hsqldb:hsql://production:9002
jdbc.username=sa
jdbc.password=root</pre><p>Therefore, the string <code class="literal">${jdbc.username}</code> is replaced
        at runtime with the value 'sa', and the same applies for other placeholder
        values that match keys in the properties file. The
        <code class="classname">PropertyPlaceholderConfigurer</code> checks for
        placeholders in most properties and attributes of a bean definition.
        Furthermore, the placeholder prefix and suffix can be customized.</p><p>With the <code class="literal">context</code> namespace introduced in Spring
        2.5, it is possible to configure property placeholders with a dedicated
        configuration element. One or more locations can be provided as a
        comma-separated list in the <code class="literal">location</code>
        attribute.</p><pre class="programlisting">&lt;<span class="hl-tag">context:property-placeholder</span> <span class="hl-attribute">location</span>=<span class="hl-value">"classpath:com/foo/jdbc.properties"</span>/&gt;</pre><p>The <code class="classname">PropertyPlaceholderConfigurer</code> not only
        looks for properties in the <code class="classname">Properties</code> file
        you specify. By default it also checks against the Java
        <code class="classname">System</code> properties if it cannot find a property
        in the specified properties files. You can customize this behavior by setting the
        <code class="literal">systemPropertiesMode</code> property of the configurer with
        one of the following three supported integer values:
        
        
        </p><div class="itemizedlist"><ul type="disc"><li><p><span class="emphasis"><em>never</em></span> (0): Never check system properties</p></li><li><p><span class="emphasis"><em>fallback</em></span> (1): Check system properties if not resolvable in the specified properties files. This is the default.</p></li><li><p><span class="emphasis"><em>override</em></span> (2): Check system properties first, before trying the specified properties files. This allows system properties to override any other property source.</p></li></ul></div><p>
        Consult the Javadoc for the <code class="classname">PropertyPlaceholderConfigurer</code>
        for more information.</p><div class="tip" style="margin-left: 0.5in; margin-right: 0.5in;"><table border="0" summary="Tip: Class name substitution"><tr><td rowspan="2" align="center" valign="top" width="25"><img alt="[Tip]" src="images/tip.gif"></td><th align="left">Class name substitution</th></tr><tr><td align="left" valign="top"><p>You can use the
          <code class="classname">PropertyPlaceholderConfigurer</code> to substitute
          class names, which is sometimes useful when you have to pick a
          particular implementation class at runtime. For example:</p><pre class="programlisting">&lt;<span class="hl-tag">bean</span> <span class="hl-attribute">class</span>=<span class="hl-value">"org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"</span>&gt;
  &lt;<span class="hl-tag">property</span> <span class="hl-attribute">name</span>=<span class="hl-value">"locations"</span>&gt;
      &lt;<span class="hl-tag">value</span>&gt;classpath:com/foo/strategy.properties&lt;<span class="hl-tag">/value</span>&gt;
  &lt;<span class="hl-tag">/property</span>&gt;
  &lt;<span class="hl-tag">property</span> <span class="hl-attribute">name</span>=<span class="hl-value">"properties"</span>&gt;
      &lt;<span class="hl-tag">value</span>&gt;custom.strategy.class=com.foo.DefaultStrategy&lt;<span class="hl-tag">/value</span>&gt;
  &lt;<span class="hl-tag">/property</span>&gt;
&lt;<span class="hl-tag">/bean</span>&gt;

&lt;<span class="hl-tag">bean</span> <span class="hl-attribute">id</span>=<span class="hl-value">"serviceStrategy"</span> <span class="hl-attribute">class</span>=<span class="hl-value">"${custom.strategy.class}"</span>/&gt;</pre><p>If the class cannot be resolved at runtime to a valid class,
          resolution of the bean fails when it is about to be created, which is
          during the <code class="methodname">preInstantiateSingletons()</code> phase
          of an <code class="interfacename">ApplicationContext</code> for a
          non-lazy-init bean.</p></td></tr></table></div></div><div class="section" lang="en"><div class="titlepage"><div><div><h4 class="title"><a name="beans-factory-overrideconfigurer"></a>4.8.2.2&nbsp;Example: the
        <code class="classname">PropertyOverrideConfigurer</code></h4></div></div></div><p>The <code class="classname">PropertyOverrideConfigurer</code>, another bean
        factory post-processor, resembles the
        <code class="interfacename">PropertyPlaceholderConfigurer</code>, but unlike
        the latter, the original definitions can have default values or no
        values at all for bean properties. If an overriding
        <code class="classname">Properties</code> file does not have an entry for a
        certain bean property, the default context definition is used.</p><p>Note that the bean definition is <span class="emphasis"><em>not</em></span> aware of
        being overridden, so it is not immediately obvious from the XML
        definition file that the override configurer is being used. In case of
        multiple <code class="classname">PropertyOverrideConfigurer</code> instances
        that define different values for the same bean property, the last one
        wins, due to the overriding mechanism.</p><p>Properties file configuration lines take this format:</p><pre class="programlisting">beanName.property=value</pre><p>For example:</p><pre class="programlisting">dataSource.driverClassName=com.mysql.jdbc.Driver
dataSource.url=jdbc:mysql:mydb</pre><p>This example file can be used with a container definition that
        contains a bean called <span class="emphasis"><em>dataSource</em></span>, which has
        <span class="emphasis"><em>driver</em></span> and <span class="emphasis"><em>url</em></span>
        properties.</p><p>Compound property names are also supported, as long as every
        component of the path except the final property being overridden is
        already non-null (presumably initialized by the constructors). In this
        example...</p><pre class="programlisting">foo.fred.bob.sammy=123</pre><p>... the <code class="literal">sammy</code> property of the
        <code class="literal">bob</code> property of the <code class="literal">fred</code> property
        of the <code class="literal">foo</code> bean is set to the scalar value
        <code class="literal">123</code>.</p><div class="note" style="margin-left: 0.5in; margin-right: 0.5in;"><table border="0" summary="Note"><tr><td rowspan="2" align="center" valign="top" width="25"><img alt="[Note]" src="images/note.gif"></td><th align="left">Note</th></tr><tr><td align="left" valign="top"><p>Specified override values are always <span class="emphasis"><em>literal</em></span>
          values; they are not translated into bean references. This convention
          also applies when the original value in the XML bean definition
          specifies a bean reference.</p></td></tr></table></div><p>With the <code class="literal">context</code> namespace introduced in Spring
        2.5, it is possible to configure property overriding with a dedicated
        configuration element:</p><pre class="programlisting">&lt;<span class="hl-tag">context:property-override</span> <span class="hl-attribute">location</span>=<span class="hl-value">"classpath:override.properties"</span>/&gt;</pre></div></div><div class="section" lang="en"><div class="titlepage"><div><div><h3 class="title"><a name="beans-factory-extension-factorybean"></a>4.8.3&nbsp;Customizing instantiation logic with a
      <code class="interfacename">FactoryBean</code></h3></div></div></div><p>Implement the
      <code class="interfacename">org.springframework.beans.factory.FactoryBean</code>
      interface for objects that <span class="emphasis"><em>are themselves
      factories</em></span>.</p><p>The <code class="interfacename">FactoryBean</code> interface is a point of
      pluggability into the Spring IoC container's instantiation logic. If you
      have complex initialization code that is better expressed in Java as
      opposed to a (potentially) verbose amount of XML, you can create your own
      <code class="interfacename">FactoryBean</code>, write the complex
      initialization inside that class, and then plug your custom
      <code class="interfacename">FactoryBean</code> into the container.</p><p>The <code class="interfacename">FactoryBean</code> interface provides
      three methods:</p><div class="itemizedlist"><ul type="disc"><li><p><code class="methodname">Object getObject()</code>: returns an instance
          of the object this factory creates. The instance can possibly be
          shared, depending on whether this factory returns singletons or
          prototypes.</p></li><li><p><code class="methodname">boolean isSingleton()</code>: returns
          <code class="literal">true</code> if this
          <code class="interfacename">FactoryBean</code> returns singletons,
          <code class="literal">false</code> otherwise.</p></li><li><p><code class="methodname">Class getObjectType()</code>: returns the object
          type returned by the <code class="methodname">getObject()</code> method or
          <code class="literal">null</code> if the type is not known in advance.</p></li></ul></div><p>The <code class="interfacename">FactoryBean</code> concept and interface
      is used in a number of places within the Spring Framework; more than 50
      implementations of the <code class="interfacename">FactoryBean</code>
      interface ship with Spring itself.</p><p>When you need to ask a container for an actual
      <code class="interfacename">FactoryBean</code> instance itself instead of the bean
      it produces, preface the bean's id with the ampersand symbol
      (<code class="literal">&amp;</code>) when calling the
      <code class="methodname">getBean()</code> method of the
      <code class="interfacename">ApplicationContext</code>. So for a given
      <code class="interfacename">FactoryBean</code> with an id of
      <code class="literal">myBean</code>, invoking <code class="literal">getBean("myBean")</code>
      on the container returns the product of the
      <code class="interfacename">FactoryBean</code>; whereas, invoking
      <code class="literal">getBean("&amp;myBean")</code> returns the
      <code class="interfacename">FactoryBean</code> instance
      itself.</p></div></div><div class="section" lang="en"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="beans-annotation-config"></a>4.9&nbsp;Annotation-based container configuration</h2></div></div></div><div class="sidebar"><p class="title"><b>Are annotations better than XML for configuring Spring?</b></p><p>The introduction of annotation-based configurations raised the
      question of whether this approach is 'better' than XML. The short answer
      is <span class="emphasis"><em>it depends</em></span>. The long answer is that each approach
      has its pros and cons, and usually it is up to the developer to decide
      which strategy suits her better. Due to the way they are defined,
      annotations provide a lot of context in their declaration, leading to
      shorter and more concise configuration. However, XML excels at wiring up
      components without touching their source code or recompiling them. Some
      developers prefer having the wiring close to the source while others argue
      that annotated classes are no longer POJOs and, furthermore, that the
      configuration becomes decentralized and harder to control.</p><p>No matter the choice, Spring can accommodate both styles and even mix
      them together. It's worth pointing out that through its <a class="link" href="beans.html#beans-java" title="4.12&nbsp;Java-based container configuration">JavaConfig</a> option, Spring allows annotations
      to be used in a non-invasive way, without touching the target components
      source code and that in terms of tooling, all configuration styles are
      supported by the <a class="ulink" href="http://www.springsource.com/products/sts" target="_top">SpringSource Tool Suite</a>.</p></div><p>An alternative to XML setups is provided by annotation-based
    configuration which rely on the bytecode metadata for wiring up components
    instead of angle-bracket declarations. Instead of using XML to describe a
    bean wiring, the developer moves the configuration into the component class
    itself by using annotations on the relevant class, method, or field
    declaration. As mentioned in <a class="xref" href="beans.html#beans-factory-extension-bpp-examples-rabpp" title="4.8.1.2&nbsp;Example: The RequiredAnnotationBeanPostProcessor">Section&nbsp;4.8.1.2, &#8220;Example: The
        RequiredAnnotationBeanPostProcessor&#8221;</a>, using a
    <code class="interfacename">BeanPostProcessor</code> in conjunction with
    annotations is a common means of extending the Spring IoC container. For
    example, Spring 2.0 introduced the possibility of enforcing required
    properties with the <a class="link" href="beans.html#beans-required-annotation" title="4.9.1&nbsp;@Required">@Required</a> annotation. As of Spring 2.5, it is now possible to follow
    that same general approach to drive Spring's dependency injection.
    Essentially, the <code class="interfacename">@Autowired</code> annotation
    provides the same capabilities as described in <a class="xref" href="beans.html#beans-factory-autowire" title="4.4.5&nbsp;Autowiring collaborators">Section&nbsp;4.4.5, &#8220;Autowiring collaborators&#8221;</a> but with more fine-grained control and
    wider applicability. Spring 2.5 also adds support for JSR-250 annotations
    such as <code class="interfacename">@Resource</code>,
    <code class="interfacename">@PostConstruct</code>, and
    <code class="interfacename">@PreDestroy</code>. Spring 3.0 adds support for
    JSR-330 (Dependency Injection for Java) annotations contained in the
    javax.inject package such as <code class="classname">@Inject</code>,
    <code class="literal">@Qualifier, @Named, and @Provider</code> if the JSR330 jar is
    present on the classpath. Use of these annotations also requires that
    certain <code class="interfacename">BeanPostProcessors</code> be registered
    within the Spring container. </p><div class="note" style="margin-left: 0.5in; margin-right: 0.5in;"><table border="0" summary="Note"><tr><td rowspan="2" align="center" valign="top" width="25"><img alt="[Note]" src="images/note.gif"></td><th align="left">Note</th></tr><tr><td align="left" valign="top"> Annotation injection is performed
    <span class="emphasis"><em>before</em></span> XML injection, thus the latter configuration
    will override the former for properties wired through both approaches.
    </td></tr></table></div><p> As always, you can register them as individual bean definitions, but
    they can also be implicitly registered by including the following tag in an
    XML-based Spring configuration (notice the inclusion of the
    <code class="literal">context</code> namespace):</p><pre class="programlisting">&lt;<span class="hl-tag">?xml version="1.0" encoding="UTF-8"?</span>&gt;
&lt;<span class="hl-tag">beans</span> <span class="hl-attribute">xmlns</span>=<span class="hl-value">"http://www.springframework.org/schema/beans"</span>
     <span class="hl-attribute">xmlns:xsi</span>=<span class="hl-value">"http://www.w3.org/2001/XMLSchema-instance"</span>
     <span class="hl-attribute">xmlns:context</span>=<span class="hl-value">"http://www.springframework.org/schema/context"</span>
     <span class="hl-attribute">xsi:schemaLocation</span>=<span class="hl-value">"http://www.springframework.org/schema/beans
         http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
         http://www.springframework.org/schema/context
         http://www.springframework.org/schema/context/spring-context-3.0.xsd"</span>&gt;

   &lt;<span class="hl-tag">context:annotation-config</span>/&gt;

&lt;<span class="hl-tag">/beans</span>&gt;</pre><p>(The implicitly registered post-processors include <a class="ulink" href="http://static.springframework.org/spring/docs/3.0.x/javadoc-api/org/springframework/beans/factory/annotation/AutowiredAnnotationBeanPostProcessor.html" target="_top"><code class="classname">AutowiredAnnotationBeanPostProcessor</code></a>, <a class="ulink" href="http://static.springframework.org/spring/docs/3.0.x/javadoc-api/org/springframework/context/annotation/CommonAnnotationBeanPostProcessor.html" target="_top"><code class="classname">CommonAnnotationBeanPostProcessor</code></a>, <a class="ulink" href="http://static.springframework.org/spring/docs/3.0.x/javadoc-api/org/springframework/orm/jpa/support/PersistenceAnnotationBeanPostProcessor.html" target="_top"><code class="classname">PersistenceAnnotationBeanPostProcessor</code></a>, as
    well as the aforementioned <a class="ulink" href="http://static.springframework.org/spring/docs/3.0.x/javadoc-api/org/springframework/beans/factory/annotation/RequiredAnnotationBeanPostProcessor.html" target="_top"><code class="classname">RequiredAnnotationBeanPostProcessor</code></a>.)</p><div class="note" style="margin-left: 0.5in; margin-right: 0.5in;"><table border="0" summary="Note"><tr><td rowspan="2" align="center" valign="top" width="25"><img alt="[Note]" src="images/note.gif"></td><th align="left">Note</th></tr><tr><td align="left" valign="top"><p><code class="literal">&lt;context:annotation-config/&gt;</code> only looks for
      annotations on beans in the same application context in which it is
      defined. This means that, if you put
      <code class="literal">&lt;context:annotation-config/&gt;</code> in a
      <code class="interfacename">WebApplicationContext</code> for a
      <code class="classname">DispatcherServlet</code>, it only checks for
      <code class="interfacename">@Autowired</code> beans in your controllers, and
      not your services. See <a class="xref" href="mvc.html#mvc-servlet" title="16.2&nbsp;The DispatcherServlet">Section&nbsp;16.2, &#8220;The DispatcherServlet&#8221;</a> for more
      information.</p></td></tr></table></div><div class="section" lang="en"><div class="titlepage"><div><div><h3 class="title"><a name="beans-required-annotation"></a>4.9.1&nbsp;<code class="interfacename">@Required</code></h3></div></div></div><p>The <code class="interfacename">@Required</code> annotation applies to
      bean property setter methods, as in the following example:</p><pre class="programlisting"><span class="hl-keyword">public</span> <span class="hl-keyword">class</span> SimpleMovieLister {

  <span class="hl-keyword">private</span> MovieFinder movieFinder;

  @Required
  <span class="hl-keyword">public</span> <span class="hl-keyword">void</span> setMovieFinder(MovieFinder movieFinder) {
      <span class="hl-keyword">this</span>.movieFinder = movieFinder;
  }

  <span class="hl-comment">// ...</span>
}</pre><p>This annotation simply indicates that the affected bean property must
      be populated at configuration time, through an explicit property value in
      a bean definition or through autowiring. The container throws an exception
      if the affected bean property has not been populated; this allows for
      eager and explicit failure, avoiding
      <code class="classname">NullPointerException</code>s or the like later on. It is
      still recommended that you put assertions into the bean class itself, for
      example, into an init method. Doing so enforces those required references
      and values even when you use the class outside of a container.</p></div><div class="section" lang="en"><div class="titlepage"><div><div><h3 class="title"><a name="beans-autowired-annotation"></a>4.9.2&nbsp;<code class="interfacename">@Autowired and @Inject</code></h3></div></div></div><p>As expected, you can apply the
      <code class="interfacename">@Autowired</code> annotation to "traditional"
      setter methods:</p><div class="note" style="margin-left: 0.5in; margin-right: 0.5in;"><table border="0" summary="Note"><tr><td rowspan="2" align="center" valign="top" width="25"><img alt="[Note]" src="images/note.gif"></td><th align="left">Note</th></tr><tr><td align="left" valign="top"><p>JSR 330's @Inject annotation can be used in place of Spring's
        <code class="interfacename">@Autowired</code> in the examples below.
        <code class="interfacename">@Inject</code> does not have a required property
        unlike Spring's <code class="interfacename">@Autowired</code> annotation
        which has a <code class="literal">required</code> property to indicate if the
        value being injected is optional. This behavior is enabled automatically
        if you have the JSR 330 JAR on the classpath.</p></td></tr></table></div><pre class="programlisting"><span class="hl-keyword">public</span> <span class="hl-keyword">class</span> SimpleMovieLister {

  <span class="hl-keyword">private</span> MovieFinder movieFinder;

  @Autowired
  <span class="hl-keyword">public</span> <span class="hl-keyword">void</span> setMovieFinder(MovieFinder movieFinder) {
      <span class="hl-keyword">this</span>.movieFinder = movieFinder;
  }

  <span class="hl-comment">// ...</span>
}</pre><p>You can also apply the annotation to methods with arbitrary names
      and/or multiple arguments:</p><pre class="programlisting"><span class="hl-keyword">public</span> <span class="hl-keyword">class</span> MovieRecommender {

  <span class="hl-keyword">private</span> MovieCatalog movieCatalog;

  <span class="hl-keyword">private</span> CustomerPreferenceDao customerPreferenceDao;

  @Autowired
  <span class="hl-keyword">public</span> <span class="hl-keyword">void</span> prepare(MovieCatalog movieCatalog,
                      CustomerPreferenceDao customerPreferenceDao) {
      <span class="hl-keyword">this</span>.movieCatalog = movieCatalog;
      <span class="hl-keyword">this</span>.customerPreferenceDao = customerPreferenceDao;
  }

  <span class="hl-comment">// ...</span>
}</pre><p>You can apply <code class="interfacename">@Autowired</code> to
      constructors and fields:</p><pre class="programlisting"><span class="hl-keyword">public</span> <span class="hl-keyword">class</span> MovieRecommender {

  @Autowired
  <span class="hl-keyword">private</span> MovieCatalog movieCatalog;

  <span class="hl-keyword">private</span> CustomerPreferenceDao customerPreferenceDao;

  @Autowired
  <span class="hl-keyword">public</span> MovieRecommender(CustomerPreferenceDao customerPreferenceDao) {
      <span class="hl-keyword">this</span>.customerPreferenceDao = customerPreferenceDao;
  }

  <span class="hl-comment">// ...</span>
}</pre><p>It is also possible to provide <span class="emphasis"><em>all</em></span> beans of a
      particular type from the <code class="interfacename">ApplicationContext</code>
      by adding the annotation to a field or method that expects an array of
      that type:</p><pre class="programlisting"><span class="hl-keyword">public</span> <span class="hl-keyword">class</span> MovieRecommender {

  @Autowired
  <span class="hl-keyword">private</span> MovieCatalog[] movieCatalogs;

  <span class="hl-comment">// ...</span>
}</pre><p>The same applies for typed collections:</p><pre class="programlisting"><span class="hl-keyword">public</span> <span class="hl-keyword">class</span> MovieRecommender {

  <span class="hl-keyword">private</span> Set&lt;MovieCatalog&gt; movieCatalogs;

  @Autowired
  <span class="hl-keyword">public</span> <span class="hl-keyword">void</span> setMovieCatalogs(Set&lt;MovieCatalog&gt; movieCatalogs) {
      <span class="hl-keyword">this</span>.movieCatalogs = movieCatalogs;
  }

  <span class="hl-comment">// ...</span>
}</pre><p>Even typed Maps can be autowired as long as the expected key type is
      <code class="classname">String</code>. The Map values will contain all beans of
      the expected type, and the keys will contain the corresponding bean
      names:</p><pre class="programlisting"><span class="hl-keyword">public</span> <span class="hl-keyword">class</span> MovieRecommender {

  <span class="hl-keyword">private</span> Map&lt;String, MovieCatalog&gt; movieCatalogs;

  @Autowired
  <span class="hl-keyword">public</span> <span class="hl-keyword">void</span> setMovieCatalogs(Map&lt;String, MovieCatalog&gt; movieCatalogs) {
      <span class="hl-keyword">this</span>.movieCatalogs = movieCatalogs;
  }

  <span class="hl-comment">// ...</span>
}</pre><p>By default, the autowiring fails whenever <span class="emphasis"><em>zero</em></span>
      candidate beans are available; the default behavior is to treat annotated
      methods, constructors, and fields as indicating
      <span class="emphasis"><em>required</em></span> dependencies. This behavior can be changed
      as demonstrated below.</p><pre class="programlisting"><span class="hl-keyword">public</span> <span class="hl-keyword">class</span> SimpleMovieLister {

  <span class="hl-keyword">private</span> MovieFinder movieFinder;

  @Autowired(required=false)
  <span class="hl-keyword">public</span> <span class="hl-keyword">void</span> setMovieFinder(MovieFinder movieFinder) {
      <span class="hl-keyword">this</span>.movieFinder = movieFinder;
  }

  <span class="hl-comment">// ...</span>
}</pre><div class="note" style="margin-left: 0.5in; margin-right: 0.5in;"><table border="0" summary="Note"><tr><td rowspan="2" align="center" valign="top" width="25"><img alt="[Note]" src="images/note.gif"></td><th align="left">Note</th></tr><tr><td align="left" valign="top"><p>Only <span class="emphasis"><em>one annotated constructor per-class</em></span> can be
        marked as <span class="emphasis"><em>required</em></span>, but multiple non-required
        constructors can be annotated. In that case, each is considered among
        the candidates and Spring uses the <span class="emphasis"><em>greediest</em></span>
        constructor whose dependencies can be satisfied, that is the constructor
        that has the largest number of arguments.</p><p><code class="interfacename">@Autowired</code>'s
        <span class="emphasis"><em>required</em></span> attribute is recommended over the
        <code class="interfacename">@Required</code> annotation. The
        <span class="emphasis"><em>required</em></span> attribute indicates that the property is
        not required for autowiring purposes, the property is ignored if it
        cannot be autowired. <code class="interfacename">@Required</code>, on the
        other hand, is stronger in that it enforces the property that was set by
        any means supported by the container. If no value is injected, a
        corresponding exception is raised.</p></td></tr></table></div><p>You can also use <code class="interfacename">@Autowired</code> for
      interfaces that are well-known resolvable dependencies:
      <code class="interfacename">BeanFactory</code>,
      <code class="interfacename">ApplicationContext</code>,
      <code class="interfacename">Environment</code>,
      <code class="interfacename">ResourceLoader</code>,
      <code class="interfacename">ApplicationEventPublisher</code>, and
      <code class="interfacename">MessageSource</code>. These interfaces and their
      extended interfaces, such as
      <code class="interfacename">ConfigurableApplicationContext</code> or
      <code class="interfacename">ResourcePatternResolver</code>, are automatically
      resolved, with no special setup necessary.</p><pre class="programlisting"><span class="hl-keyword">public</span> <span class="hl-keyword">class</span> MovieRecommender {

  @Autowired
  <span class="hl-keyword">private</span> ApplicationContext context;

  <span class="hl-keyword">public</span> MovieRecommender() {
  }

  <span class="hl-comment">// ...</span>
}</pre><div class="note" style="margin-left: 0.5in; margin-right: 0.5in;"><table border="0" summary="Note"><tr><td rowspan="2" align="center" valign="top" width="25"><img alt="[Note]" src="images/note.gif"></td><th align="left">Note</th></tr><tr><td align="left" valign="top"><p>
        <code class="interfacename">@Autowired</code>,
        <code class="interfacename">@Inject</code>,
        <code class="interfacename">@Resource</code>, and
        <code class="interfacename">@Value</code> annotations are handled by a
        Spring <code class="interfacename">BeanPostProcessor</code> implementations
        which in turn means that you <span class="emphasis"><em>cannot</em></span>
        apply these annotations within your own
        <code class="classname">BeanPostProcessor</code> or
        <code class="classname">BeanFactoryPostProcessor</code> types (if any). These
        types must be 'wired up' explicitly via XML or using a Spring
        <code class="interfacename">@Bean</code> method.</p></td></tr></table></div></div><div class="section" lang="en"><div class="titlepage"><div><div><h3 class="title"><a name="beans-autowired-annotation-qualifiers"></a>4.9.3&nbsp;Fine-tuning annotation-based autowiring with qualifiers</h3></div></div></div><p>Because autowiring by type may lead to multiple candidates, it is
      often necessary to have more control over the selection process. One way
      to accomplish this is with Spring's
      <code class="interfacename">@Qualifier</code> annotation. You can associate
      qualifier values with specific arguments, narrowing the set of type
      matches so that a specific bean is chosen for each argument. In the
      simplest case, this can be a plain descriptive value:</p><div class="note" style="margin-left: 0.5in; margin-right: 0.5in;"><table border="0" summary="Note"><tr><td rowspan="2" align="center" valign="top" width="25"><img alt="[Note]" src="images/note.gif"></td><th align="left">Note</th></tr><tr><td align="left" valign="top"><p>JSR 330's <code class="interfacename">@Qualifier</code> annotation can
        only be applied as a meta-annotation unlike Spring's @Qualifier which
        takes a string property to discriminate among multiple injection
        candidates and can be placed on annotations as well as types, fields,
        methods, constructors, and parameters.</p></td></tr></table></div><pre class="programlisting"><span class="hl-keyword">public</span> <span class="hl-keyword">class</span> MovieRecommender {

  @Autowired
  @Qualifier(<span class="hl-string">"main"</span>)
  <span class="hl-keyword">private</span> MovieCatalog movieCatalog;

  <span class="hl-comment">// ...</span>
}</pre><p>The <code class="interfacename">@Qualifier</code> annotation can also be
      specified on individual constructor arguments or method parameters:</p><pre class="programlisting"><span class="hl-keyword">public</span> <span class="hl-keyword">class</span> MovieRecommender {

  <span class="hl-keyword">private</span> MovieCatalog movieCatalog;

  <span class="hl-keyword">private</span> CustomerPreferenceDao customerPreferenceDao;

  @Autowired
  <span class="hl-keyword">public</span> <span class="hl-keyword">void</span> prepare(@Qualifier(<span class="hl-string">"main"</span>) MovieCatalog movieCatalog,
                      CustomerPreferenceDao customerPreferenceDao) {
      <span class="hl-keyword">this</span>.movieCatalog = movieCatalog;
      <span class="hl-keyword">this</span>.customerPreferenceDao = customerPreferenceDao;
  }

  <span class="hl-comment">// ...</span>
}</pre><p>The corresponding bean definitions appear as follows. The bean with
      qualifier value "main" is wired with the constructor argument that is
      qualified with the same value.</p><pre class="programlisting">&lt;<span class="hl-tag">?xml version="1.0" encoding="UTF-8"?</span>&gt;
&lt;<span class="hl-tag">beans</span> <span class="hl-attribute">xmlns</span>=<span class="hl-value">"http://www.springframework.org/schema/beans"</span>
  <span class="hl-attribute">xmlns:xsi</span>=<span class="hl-value">"http://www.w3.org/2001/XMLSchema-instance"</span>
  <span class="hl-attribute">xmlns:context</span>=<span class="hl-value">"http://www.springframework.org/schema/context"</span>
  <span class="hl-attribute">xsi:schemaLocation</span>=<span class="hl-value">"http://www.springframework.org/schema/beans
      http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
      http://www.springframework.org/schema/context
      http://www.springframework.org/schema/context/spring-context-3.0.xsd"</span>&gt;

  &lt;<span class="hl-tag">context:annotation-config</span>/&gt;

  &lt;<span class="hl-tag">bean</span> <span class="hl-attribute">class</span>=<span class="hl-value">"example.SimpleMovieCatalog"</span>&gt;
      &lt;<span class="hl-tag">qualifier</span> <span class="hl-attribute">value</span>=<span class="hl-value">"main"</span>/&gt;
      &lt;<span class="hl-comment">!-- inject any dependencies required by this bean --</span>&gt;
  &lt;<span class="hl-tag">/bean</span>&gt;

  &lt;<span class="hl-tag">bean</span> <span class="hl-attribute">class</span>=<span class="hl-value">"example.SimpleMovieCatalog"</span>&gt;
      &lt;<span class="hl-tag">qualifier</span> <span class="hl-attribute">value</span>=<span class="hl-value">"action"</span>/&gt;
      &lt;<span class="hl-comment">!-- inject any dependencies required by this bean --</span>&gt;
  &lt;<span class="hl-tag">/bean</span>&gt;

  &lt;<span class="hl-tag">bean</span> <span class="hl-attribute">id</span>=<span class="hl-value">"movieRecommender"</span> <span class="hl-attribute">class</span>=<span class="hl-value">"example.MovieRecommender"</span>/&gt;

&lt;<span class="hl-tag">/beans</span>&gt;
</pre><p>For a fallback match, the bean name is considered a default qualifier
      value. Thus you can define the bean with an id "main" instead of the
      nested qualifier element, leading to the same matching result. However,
      although you can use this convention to refer to specific beans by name,
      <code class="interfacename">@Autowired</code> is fundamentally about
      type-driven injection with optional semantic qualifiers. This means that
      qualifier values, even with the bean name fallback, always have narrowing
      semantics within the set of type matches; they do not semantically express
      a reference to a unique bean id. Good qualifier values are "main" or
      "EMEA" or "persistent", expressing characteristics of a specific component
      that are independent from the bean id, which may be auto-generated in case
      of an anonymous bean definition like the one in the preceding
      example.</p><p>Qualifiers also apply to typed collections, as discussed above, for
      example, to <code class="literal">Set&lt;MovieCatalog&gt;</code>. In this case, all
      matching beans according to the declared qualifiers are injected as a
      collection. This implies that qualifiers do not have to be unique; they
      rather simply constitute filtering criteria. For example, you can define
      multiple <code class="classname">MovieCatalog</code> beans with the same qualifier
      value "action"; all of which would be injected into a
      <code class="literal">Set&lt;MovieCatalog&gt;</code> annotated with
      <code class="literal">@Qualifier("action")</code>.</p><div class="tip" style="margin-left: 0.5in; margin-right: 0.5in;"><table border="0" summary="Tip"><tr><td rowspan="2" align="center" valign="top" width="25"><img alt="[Tip]" src="images/tip.gif"></td><th align="left">Tip</th></tr><tr><td align="left" valign="top"><p>If you intend to express annotation-driven injection by name, do not
        primarily use <code class="interfacename">@Autowired</code>, even if is
        technically capable of referring to a bean name through
        <code class="interfacename">@Qualifier</code> values. Instead, use the
        JSR-250 <code class="interfacename">@Resource</code> annotation, which is
        semantically defined to identify a specific target component by its
        unique name, with the declared type being irrelevant for the matching
        process.</p><p>As a specific consequence of this semantic difference, beans that
        are themselves defined as a collection or map type cannot be injected
        through <code class="interfacename">@Autowired</code>, because type matching
        is not properly applicable to them. Use
        <code class="interfacename">@Resource</code> for such beans, referring to
        the specific collection or map bean by unique name.</p><p><code class="interfacename">@Autowired</code> applies to fields,
        constructors, and multi-argument methods, allowing for narrowing through
        qualifier annotations at the parameter level. By contrast,
        <code class="interfacename">@Resource</code> is supported only for fields
        and bean property setter methods with a single argument. As a
        consequence, stick with qualifiers if your injection target is a
        constructor or a multi-argument method.</p></td></tr></table></div><p>You can create your own custom qualifier annotations. Simply define an
      annotation and provide the <code class="interfacename">@Qualifier</code>
      annotation within your definition:</p><div class="note" style="margin-left: 0.5in; margin-right: 0.5in;"><table border="0" summary="Note"><tr><td rowspan="2" align="center" valign="top" width="25"><img alt="[Note]" src="images/note.gif"></td><th align="left">Note</th></tr><tr><td align="left" valign="top"><p>You can use JSR 330's <code class="interfacename">@Qualifier
        </code>annotation in the manner described below in place of
        Spring's <code class="interfacename">@Qualifier</code> annotation. This
        behavior is enabled automatically if you have the JSR 330 jar on the
        classpath.</p></td></tr></table></div><pre class="programlisting">@Target({ElementType.FIELD, ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
@Qualifier
<span class="hl-keyword">public</span> @<span class="hl-keyword">interface</span> Genre {

  String value();
}</pre><p>Then you can provide the custom qualifier on autowired fields and
      parameters:</p><pre class="programlisting"><span class="hl-keyword">public</span> <span class="hl-keyword">class</span> MovieRecommender {

  @Autowired
  @Genre(<span class="hl-string">"Action"</span>)
  <span class="hl-keyword">private</span> MovieCatalog actionCatalog;

  <span class="hl-keyword">private</span> MovieCatalog comedyCatalog;

  @Autowired
  <span class="hl-keyword">public</span> <span class="hl-keyword">void</span> setComedyCatalog(@Genre(<span class="hl-string">"Comedy"</span>) MovieCatalog comedyCatalog) {
      <span class="hl-keyword">this</span>.comedyCatalog = comedyCatalog;
  }

  <span class="hl-comment">// ...</span>
}</pre><p>Next, provide the information for the candidate bean definitions. You
      can add <code class="literal">&lt;qualifier/&gt;</code> tags as sub-elements of the
      <code class="literal">&lt;bean/&gt;</code> tag and then specify the
      <code class="literal">type</code> and <code class="literal">value</code> to match your custom
      qualifier annotations. The type is matched against the fully-qualified
      class name of the annotation. Or, as a convenience if no risk of
      conflicting names exists, you can use the short class name. Both
      approaches are demonstrated in the following example.</p><pre class="programlisting">&lt;<span class="hl-tag">?xml version="1.0" encoding="UTF-8"?</span>&gt;
&lt;<span class="hl-tag">beans</span> <span class="hl-attribute">xmlns</span>=<span class="hl-value">"http://www.springframework.org/schema/beans"</span>
  <span class="hl-attribute">xmlns:xsi</span>=<span class="hl-value">"http://www.w3.org/2001/XMLSchema-instance"</span>
  <span class="hl-attribute">xmlns:context</span>=<span class="hl-value">"http://www.springframework.org/schema/context"</span>
  <span class="hl-attribute">xsi:schemaLocation</span>=<span class="hl-value">"http://www.springframework.org/schema/beans
      http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
      http://www.springframework.org/schema/context
      http://www.springframework.org/schema/context/spring-context-3.0.xsd"</span>&gt;

  &lt;<span class="hl-tag">context:annotation-config</span>/&gt;

  &lt;<span class="hl-tag">bean</span> <span class="hl-attribute">class</span>=<span class="hl-value">"example.SimpleMovieCatalog"</span>&gt;
      &lt;<span class="hl-tag">qualifier</span> <span class="hl-attribute">type</span>=<span class="hl-value">"Genre"</span> <span class="hl-attribute">value</span>=<span class="hl-value">"Action"</span>/&gt;
      &lt;<span class="hl-comment">!-- inject any dependencies required by this bean --</span>&gt;
  &lt;<span class="hl-tag">/bean</span>&gt;

  &lt;<span class="hl-tag">bean</span> <span class="hl-attribute">class</span>=<span class="hl-value">"example.SimpleMovieCatalog"</span>&gt;
      &lt;<span class="hl-tag">qualifier</span> <span class="hl-attribute">type</span>=<span class="hl-value">"example.Genre"</span> <span class="hl-attribute">value</span>=<span class="hl-value">"Comedy"</span>/&gt;
      &lt;<span class="hl-comment">!-- inject any dependencies required by this bean --</span>&gt;
  &lt;<span class="hl-tag">/bean</span>&gt;

  &lt;<span class="hl-tag">bean</span> <span class="hl-attribute">id</span>=<span class="hl-value">"movieRecommender"</span> <span class="hl-attribute">class</span>=<span class="hl-value">"example.MovieRecommender"</span>/&gt;

&lt;<span class="hl-tag">/beans</span>&gt;
</pre><p>In <a class="xref" href="beans.html#beans-classpath-scanning" title="4.10&nbsp;Classpath scanning and managed components">Section&nbsp;4.10, &#8220;Classpath scanning and managed components&#8221;</a>, you will see an
      annotation-based alternative to providing the qualifier metadata in XML.
      Specifically, see <a class="xref" href="beans.html#beans-scanning-qualifiers" title="4.10.7&nbsp;Providing qualifier metadata with annotations">Section&nbsp;4.10.7, &#8220;Providing qualifier metadata with annotations&#8221;</a>.</p><p>In some cases, it may be sufficient to use an annotation without a
      value. This may be useful when the annotation serves a more generic
      purpose and can be applied across several different types of dependencies.
      For example, you may provide an <span class="emphasis"><em>offline</em></span> catalog that
      would be searched when no Internet connection is available. First define
      the simple annotation:</p><pre class="programlisting">@Target({ElementType.FIELD, ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
@Qualifier
<span class="hl-keyword">public</span> @<span class="hl-keyword">interface</span> Offline {

}</pre><p>Then add the annotation to the field or property to be
      autowired:</p><pre class="programlisting"><span class="hl-keyword">public</span> <span class="hl-keyword">class</span> MovieRecommender {

  @Autowired
  @Offline
  <span class="hl-keyword">private</span> MovieCatalog offlineCatalog;

  <span class="hl-comment">// ...</span>
}</pre><p>Now the bean definition only needs a qualifier
      <code class="literal">type</code>:</p><pre class="programlisting">&lt;<span class="hl-tag">bean</span> <span class="hl-attribute">class</span>=<span class="hl-value">"example.SimpleMovieCatalog"</span>&gt;
  &lt;<span class="hl-tag">qualifier</span> <span class="hl-attribute">type</span>=<span class="hl-value">"Offline"</span>/&gt;
  &lt;<span class="hl-comment">!-- inject any dependencies required by this bean --</span>&gt;
&lt;<span class="hl-tag">/bean</span>&gt;</pre><p>You can also define custom qualifier annotations that accept named
      attributes in addition to or instead of the simple
      <code class="literal">value</code> attribute. If multiple attribute values are then
      specified on a field or parameter to be autowired, a bean definition must
      match <span class="emphasis"><em>all</em></span> such attribute values to be considered an
      autowire candidate. As an example, consider the following annotation
      definition:</p><pre class="programlisting">@Target({ElementType.FIELD, ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
@Qualifier
<span class="hl-keyword">public</span> @<span class="hl-keyword">interface</span> MovieQualifier {

  String genre();

  Format format();
}</pre><p>In this case <code class="literal">Format</code> is an enum:</p><pre class="programlisting"><span class="hl-keyword">public</span> enum Format {

  VHS, DVD, BLURAY
}</pre><p>The fields to be autowired are annotated with the custom qualifier and
      include values for both attributes: <code class="literal">genre</code> and
      <code class="literal">format</code>.</p><pre class="programlisting"><span class="hl-keyword">public</span> <span class="hl-keyword">class</span> MovieRecommender {

  @Autowired
  @MovieQualifier(format=Format.VHS, genre=<span class="hl-string">"Action"</span>)
  <span class="hl-keyword">private</span> MovieCatalog actionVhsCatalog;

  @Autowired
  @MovieQualifier(format=Format.VHS, genre=<span class="hl-string">"Comedy"</span>)
  <span class="hl-keyword">private</span> MovieCatalog comedyVhsCatalog;

  @Autowired
  @MovieQualifier(format=Format.DVD, genre=<span class="hl-string">"Action"</span>)
  <span class="hl-keyword">private</span> MovieCatalog actionDvdCatalog;

  @Autowired
  @MovieQualifier(format=Format.BLURAY, genre=<span class="hl-string">"Comedy"</span>)
  <span class="hl-keyword">private</span> MovieCatalog comedyBluRayCatalog;

  <span class="hl-comment">// ...</span>
}</pre><p>Finally, the bean definitions should contain matching qualifier
      values. This example also demonstrates that bean <span class="emphasis"><em>meta</em></span>
      attributes may be used instead of the
      <code class="literal">&lt;qualifier/&gt;</code> sub-elements. If available, the
      <code class="literal">&lt;qualifier/&gt;</code> and its attributes take precedence,
      but the autowiring mechanism falls back on the values provided within the
      <code class="literal">&lt;meta/&gt;</code> tags if no such qualifier is present, as
      in the last two bean definitions in the following example.</p><pre class="programlisting">&lt;<span class="hl-tag">?xml version="1.0" encoding="UTF-8"?</span>&gt;
&lt;<span class="hl-tag">beans</span> <span class="hl-attribute">xmlns</span>=<span class="hl-value">"http://www.springframework.org/schema/beans"</span>
  <span class="hl-attribute">xmlns:xsi</span>=<span class="hl-value">"http://www.w3.org/2001/XMLSchema-instance"</span>
  <span class="hl-attribute">xmlns:context</span>=<span class="hl-value">"http://www.springframework.org/schema/context"</span>
  <span class="hl-attribute">xsi:schemaLocation</span>=<span class="hl-value">"http://www.springframework.org/schema/beans
      http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
      http://www.springframework.org/schema/context
      http://www.springframework.org/schema/context/spring-context-3.0.xsd"</span>&gt;

  &lt;<span class="hl-tag">context:annotation-config</span>/&gt;

  &lt;<span class="hl-tag">bean</span> <span class="hl-attribute">class</span>=<span class="hl-value">"example.SimpleMovieCatalog"</span>&gt;
      &lt;<span class="hl-tag">qualifier</span> <span class="hl-attribute">type</span>=<span class="hl-value">"MovieQualifier"</span>&gt;
          &lt;<span class="hl-tag">attribute</span> <span class="hl-attribute">key</span>=<span class="hl-value">"format"</span> <span class="hl-attribute">value</span>=<span class="hl-value">"VHS"</span>/&gt;
          &lt;<span class="hl-tag">attribute</span> <span class="hl-attribute">key</span>=<span class="hl-value">"genre"</span> <span class="hl-attribute">value</span>=<span class="hl-value">"Action"</span>/&gt;
      &lt;<span class="hl-tag">/qualifier</span>&gt;
      &lt;<span class="hl-comment">!-- inject any dependencies required by this bean --</span>&gt;
  &lt;<span class="hl-tag">/bean</span>&gt;

  &lt;<span class="hl-tag">bean</span> <span class="hl-attribute">class</span>=<span class="hl-value">"example.SimpleMovieCatalog"</span>&gt;
      &lt;<span class="hl-tag">qualifier</span> <span class="hl-attribute">type</span>=<span class="hl-value">"MovieQualifier"</span>&gt;
          &lt;<span class="hl-tag">attribute</span> <span class="hl-attribute">key</span>=<span class="hl-value">"format"</span> <span class="hl-attribute">value</span>=<span class="hl-value">"VHS"</span>/&gt;
          &lt;<span class="hl-tag">attribute</span> <span class="hl-attribute">key</span>=<span class="hl-value">"genre"</span> <span class="hl-attribute">value</span>=<span class="hl-value">"Comedy"</span>/&gt;
      &lt;<span class="hl-tag">/qualifier</span>&gt;
      &lt;<span class="hl-comment">!-- inject any dependencies required by this bean --</span>&gt;
  &lt;<span class="hl-tag">/bean</span>&gt;

  &lt;<span class="hl-tag">bean</span> <span class="hl-attribute">class</span>=<span class="hl-value">"example.SimpleMovieCatalog"</span>&gt;
      &lt;<span class="hl-tag">meta</span> <span class="hl-attribute">key</span>=<span class="hl-value">"format"</span> <span class="hl-attribute">value</span>=<span class="hl-value">"DVD"</span>/&gt;
      &lt;<span class="hl-tag">meta</span> <span class="hl-attribute">key</span>=<span class="hl-value">"genre"</span> <span class="hl-attribute">value</span>=<span class="hl-value">"Action"</span>/&gt;
      &lt;<span class="hl-comment">!-- inject any dependencies required by this bean --</span>&gt;
  &lt;<span class="hl-tag">/bean</span>&gt;

  &lt;<span class="hl-tag">bean</span> <span class="hl-attribute">class</span>=<span class="hl-value">"example.SimpleMovieCatalog"</span>&gt;
      &lt;<span class="hl-tag">meta</span> <span class="hl-attribute">key</span>=<span class="hl-value">"format"</span> <span class="hl-attribute">value</span>=<span class="hl-value">"BLURAY"</span>/&gt;
      &lt;<span class="hl-tag">meta</span> <span class="hl-attribute">key</span>=<span class="hl-value">"genre"</span> <span class="hl-attribute">value</span>=<span class="hl-value">"Comedy"</span>/&gt;
      &lt;<span class="hl-comment">!-- inject any dependencies required by this bean --</span>&gt;
  &lt;<span class="hl-tag">/bean</span>&gt;

&lt;<span class="hl-tag">/beans</span>&gt;</pre></div><div class="section" lang="en"><div class="titlepage"><div><div><h3 class="title"><a name="beans-custom-autowire-configurer"></a>4.9.4&nbsp;<code class="classname">CustomAutowireConfigurer</code></h3></div></div></div><p>The <a class="ulink" href="http://static.springframework.org/spring/docs/3.0.x/javadoc-api/org/springframework/beans/factory/annotation/CustomAutowireConfigurer.html" target="_top"><code class="classname">CustomAutowireConfigurer</code></a> is a
      <code class="interfacename">BeanFactoryPostProcessor</code> that enables you
      to register your own custom qualifier annotation types even if they are
      not annotated with Spring's <code class="interfacename">@Qualifier</code>
      annotation.</p><pre class="programlisting">&lt;<span class="hl-tag">bean</span> <span class="hl-attribute">id</span>=<span class="hl-value">"customAutowireConfigurer"</span>
     <span class="hl-attribute">class</span>=<span class="hl-value">"org.springframework.beans.factory.annotation.CustomAutowireConfigurer"</span>&gt;
  &lt;<span class="hl-tag">property</span> <span class="hl-attribute">name</span>=<span class="hl-value">"customQualifierTypes"</span>&gt;
      &lt;<span class="hl-tag">set</span>&gt;
          &lt;<span class="hl-tag">value</span>&gt;example.CustomQualifier&lt;<span class="hl-tag">/value</span>&gt;
      &lt;<span class="hl-tag">/set</span>&gt;
  &lt;<span class="hl-tag">/property</span>&gt;
&lt;<span class="hl-tag">/bean</span>&gt;</pre><p>The particular implementation of
      <code class="interfacename">AutowireCandidateResolver</code> that is activated
      for the application context depends on the Java version. In versions
      earlier than Java 5, the qualifier annotations are not supported, and
      therefore autowire candidates are solely determined by the
      <code class="literal">autowire-candidate</code> value of each bean definition as
      well as by any <code class="literal">default-autowire-candidates</code> pattern(s)
      available on the <code class="literal">&lt;beans/&gt;</code> element. In Java 5 or
      later, the presence of <code class="interfacename">@Qualifier</code>
      annotations and any custom annotations registered with the
      <code class="classname">CustomAutowireConfigurer</code> will also play a
      role.</p><p>Regardless of the Java version, when multiple beans qualify as
      autowire candidates, the determination of a "primary" candidate is the
      same: if exactly one bean definition among the candidates has a
      <code class="literal">primary</code> attribute set to <code class="literal">true</code>, it
      will be selected.</p></div><div class="section" lang="en"><div class="titlepage"><div><div><h3 class="title"><a name="beans-resource-annotation"></a>4.9.5&nbsp;<code class="interfacename">@Resource</code></h3></div></div></div><p>Spring also supports injection using the JSR-250
      <code class="interfacename">@Resource</code> annotation on fields or bean
      property setter methods. This is a common pattern in Java EE 5 and 6, for
      example in JSF 1.2 managed beans or JAX-WS 2.0 endpoints. Spring supports
      this pattern for Spring-managed objects as well.</p><p><code class="interfacename">@Resource</code> takes a name attribute, and
      by default Spring interprets that value as the bean name to be injected.
      In other words, it follows <span class="emphasis"><em>by-name</em></span> semantics, as
      demonstrated in this example:</p><pre class="programlisting"><span class="hl-keyword">public</span> <span class="hl-keyword">class</span> SimpleMovieLister {

  <span class="hl-keyword">private</span> MovieFinder movieFinder;

  @Resource(name=<span class="hl-string">"myMovieFinder"</span>)
  <span class="hl-keyword">public</span> <span class="hl-keyword">void</span> setMovieFinder(MovieFinder movieFinder) {
      <span class="hl-keyword">this</span>.movieFinder = movieFinder;
  }
}</pre><p>If no name is specified explicitly, the default name is derived from
      the field name or setter method. In case of a field, it takes the field
      name; in case of a setter method, it takes the bean property name. So the
      following example is going to have the bean with name "movieFinder"
      injected into its setter method:</p><pre class="programlisting"><span class="hl-keyword">public</span> <span class="hl-keyword">class</span> SimpleMovieLister {

  <span class="hl-keyword">private</span> MovieFinder movieFinder;

  @Resource
  <span class="hl-keyword">public</span> <span class="hl-keyword">void</span> setMovieFinder(MovieFinder movieFinder) {
      <span class="hl-keyword">this</span>.movieFinder = movieFinder;
  }
}</pre><div class="note" style="margin-left: 0.5in; margin-right: 0.5in;"><table border="0" summary="Note"><tr><td rowspan="2" align="center" valign="top" width="25"><img alt="[Note]" src="images/note.gif"></td><th align="left">Note</th></tr><tr><td align="left" valign="top"><p>The name provided with the annotation is resolved as a bean name by
        the <code class="interfacename">ApplicationContext</code> of which the
        <code class="classname">CommonAnnotationBeanPostProcessor</code> is aware. The
        names can be resolved through JNDI if you configure Spring's <a class="ulink" href="http://static.springframework.org/spring/docs/3.0.x/javadoc-api/org/springframework/jndi/support/SimpleJndiBeanFactory.html" target="_top"><code class="classname">SimpleJndiBeanFactory</code></a> explicitly.
        However, it is recommended that you rely on the default behavior and
        simply use Spring's JNDI lookup capabilities to preserve the level of
        indirection.</p></td></tr></table></div><p>In the exclusive case of <code class="interfacename">@Resource</code>
      usage with no explicit name specified, and similar to
      <code class="interfacename">@Autowired</code>,
      <code class="interfacename">@Resource</code> finds a primary type match
      instead of a specific named bean and resolves well-known resolvable
      dependencies: the
      <code class="interfacename">BeanFactory</code><code class="interfacename">,
      ApplicationContext,</code><code class="interfacename"> ResourceLoader,
      ApplicationEventPublisher</code>, and
      <code class="interfacename">MessageSource</code> interfaces.</p><p>Thus in the following example, the
      <code class="literal">customerPreferenceDao</code> field first looks for a bean
      named customerPreferenceDao, then falls back to a primary type match for
      the type <code class="classname">CustomerPreferenceDao</code>. The "context" field
      is injected based on the known resolvable dependency type
      <code class="interfacename">ApplicationContext</code>.</p><pre class="programlisting"><span class="hl-keyword">public</span> <span class="hl-keyword">class</span> MovieRecommender {

  @Resource
  <span class="hl-keyword">private</span> CustomerPreferenceDao customerPreferenceDao;

  @Resource
  <span class="hl-keyword">private</span> ApplicationContext context;

  <span class="hl-keyword">public</span> MovieRecommender() {
  }

  <span class="hl-comment">// ...</span>
}</pre></div><div class="section" lang="en"><div class="titlepage"><div><div><h3 class="title"><a name="beans-postconstruct-and-predestroy-annotations"></a>4.9.6&nbsp;<code class="interfacename">@PostConstruct</code> and
      <code class="interfacename">@PreDestroy</code></h3></div></div></div><p>The <code class="classname">CommonAnnotationBeanPostProcessor</code> not only
      recognizes the <code class="interfacename">@Resource</code> annotation but
      also the JSR-250 <span class="emphasis"><em>lifecycle</em></span> annotations. Introduced in
      Spring 2.5, the support for these annotations offers yet another
      alternative to those described in <a class="link" href="beans.html#beans-factory-lifecycle-initializingbean" title="4.6.1.1&nbsp;Initialization callbacks">initialization
      callbacks</a> and <a class="link" href="beans.html#beans-factory-lifecycle-disposablebean" title="4.6.1.2&nbsp;Destruction callbacks">destruction
      callbacks</a>. Provided that the
      <code class="classname">CommonAnnotationBeanPostProcessor</code> is registered
      within the Spring <code class="interfacename">ApplicationContext</code>, a
      method carrying one of these annotations is invoked at the same point in
      the lifecycle as the corresponding Spring lifecycle interface method or
      explicitly declared callback method. In the example below, the cache will
      be pre-populated upon initialization and cleared upon destruction.</p><pre class="programlisting"><span class="hl-keyword">public</span> <span class="hl-keyword">class</span> CachingMovieLister {

  @PostConstruct
  <span class="hl-keyword">public</span> <span class="hl-keyword">void</span> populateMovieCache() {
      <span class="hl-comment">// populates the movie cache upon initialization...</span>
  }

  @PreDestroy
  <span class="hl-keyword">public</span> <span class="hl-keyword">void</span> clearMovieCache() {
      <span class="hl-comment">// clears the movie cache upon destruction...</span>
  }
}</pre><div class="note" style="margin-left: 0.5in; margin-right: 0.5in;"><table border="0" summary="Note"><tr><td rowspan="2" align="center" valign="top" width="25"><img alt="[Note]" src="images/note.gif"></td><th align="left">Note</th></tr><tr><td align="left" valign="top"><p>For details about the effects of combining various lifecycle
        mechanisms, see <a class="xref" href="beans.html#beans-factory-lifecycle-combined-effects" title="4.6.1.4&nbsp;Combining lifecycle mechanisms">Section&nbsp;4.6.1.4, &#8220;Combining lifecycle mechanisms&#8221;</a>.</p></td></tr></table></div></div></div><div class="section" lang="en"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="beans-classpath-scanning"></a>4.10&nbsp;Classpath scanning and managed components</h2></div></div></div><p>Most examples foo bar in this chapter use XML to specify the
    configuration metadata that produces each
    <code class="interfacename">BeanDefinition</code> within the Spring container.
    The previous section (<a class="xref" href="beans.html#beans-annotation-config" title="4.9&nbsp;Annotation-based container configuration">Section&nbsp;4.9, &#8220;Annotation-based container configuration&#8221;</a>)
    demonstrates how to provide a lot of the configuration metadata through
    source-level annotations. Even in those examples, however, the "base" bean
    definitions are explicitly defined in the XML file, while the annotations
    only drive the dependency injection. This section describes an option for
    implicitly detecting the <span class="emphasis"><em>candidate components</em></span> by
    scanning the classpath. Candidate components are classes that match against
    a filter criteria and have a corresponding bean definition registered with
    the container. This removes the need to use XML to perform bean
    registration, instead you can use annotations (for example @Component),
    AspectJ type expressions, or your own custom filter criteria to select which
    classes will have bean definitions registered with the container.</p><div class="note" style="margin-left: 0.5in; margin-right: 0.5in;"><table border="0" summary="Note"><tr><td rowspan="2" align="center" valign="top" width="25"><img alt="[Note]" src="images/note.gif"></td><th align="left">Note</th></tr><tr><td align="left" valign="top"><p>Starting with Spring 3.0, many features provided by the <a class="ulink" href="http://www.springsource.org/javaconfig" target="_top">Spring JavaConfig
      project</a> are part of the core Spring Framework. This allows you to
      define beans using Java rather than using the traditional XML files. Take
      a look at the <code class="interfacename">@Configuration</code>,
      <code class="interfacename">@Bean</code>,
      <code class="interfacename">@Import</code>, and
      <code class="interfacename">@DependsOn</code> annotations for examples of how
      to use these new features.</p></td></tr></table></div><div class="section" lang="en"><div class="titlepage"><div><div><h3 class="title"><a name="beans-stereotype-annotations"></a>4.10.1&nbsp;<code class="interfacename">@Component</code> and further stereotype
      annotations</h3></div></div></div><p>In Spring 2.0 and later, the
      <code class="interfacename">@Repository</code> annotation is a marker for any
      class that fulfills the role or <span class="emphasis"><em>stereotype</em></span> (also
      known as Data Access Object or DAO) of a repository. Among the uses of
      this marker is the automatic translation of exceptions as described in
      <a class="xref" href="orm.html#orm-exception-translation" title="14.2.2&nbsp;Exception translation">Section&nbsp;14.2.2, &#8220;Exception translation&#8221;</a>.</p><p>Spring 2.5 introduces further stereotype annotations:
      <code class="interfacename">@Component</code>,
      <code class="interfacename">@Service</code>, and
      <code class="interfacename">@Controller</code>.
      <code class="interfacename">@Component</code> is a generic stereotype for any
      Spring-managed component. <code class="interfacename">@Repository</code>,
      <code class="interfacename">@Service</code>, and
      <code class="interfacename">@Controller</code> are specializations of
      <code class="interfacename">@Component</code> for more specific use cases, for
      example, in the persistence, service, and presentation layers,
      respectively. Therefore, you can annotate your component classes with
      <code class="interfacename">@Component</code>, but by annotating them with
      <code class="interfacename">@Repository</code>,
      <code class="interfacename">@Service</code>, or
      <code class="interfacename">@Controller</code> instead, your classes are more
      properly suited for processing by tools or associating with aspects. For
      example, these stereotype annotations make ideal targets for pointcuts. It
      is also possible that <code class="interfacename">@Repository</code>,
      <code class="interfacename">@Service</code>, and
      <code class="interfacename">@Controller</code> may carry additional semantics
      in future releases of the Spring Framework. Thus, if you are choosing
      between using <code class="interfacename">@Component</code> or
      <code class="interfacename">@Service</code> for your service layer,
      <code class="interfacename">@Service</code> is clearly the better choice.
      Similarly, as stated above, <code class="interfacename">@Repository</code> is
      already supported as a marker for automatic exception translation in your
      persistence layer.</p></div><div class="section" lang="en"><div class="titlepage"><div><div><h3 class="title"><a name="beans-scanning-autodetection"></a>4.10.2&nbsp;Automatically detecting classes and registering bean
      definitions</h3></div></div></div><p>Spring can automatically detect stereotyped classes and register
      corresponding <code class="interfacename">BeanDefinition</code>s with the
      <code class="interfacename">ApplicationContext</code>. For example, the
      following two classes are eligible for such autodetection:</p><pre class="programlisting">@Service
<span class="hl-keyword">public</span> <span class="hl-keyword">class</span> SimpleMovieLister {

  <span class="hl-keyword">private</span> MovieFinder movieFinder;

  @Autowired
  <span class="hl-keyword">public</span> SimpleMovieLister(MovieFinder movieFinder) {
      <span class="hl-keyword">this</span>.movieFinder = movieFinder;
  }
}</pre><pre class="programlisting">@Repository
<span class="hl-keyword">public</span> <span class="hl-keyword">class</span> JpaMovieFinder <span class="hl-keyword">implements</span> MovieFinder {
  <span class="hl-comment">// implementation elided for clarity</span>
}</pre><p>To autodetect these classes and register the corresponding beans, you
      need to include the following element in XML, where the base-package
      element is a common parent package for the two classes. (Alternatively,
      you can specify a comma-separated list that includes the parent package of
      each class.)</p><pre class="programlisting">&lt;<span class="hl-tag">?xml version="1.0" encoding="UTF-8"?</span>&gt;
&lt;<span class="hl-tag">beans</span> <span class="hl-attribute">xmlns</span>=<span class="hl-value">"http://www.springframework.org/schema/beans"</span>
     <span class="hl-attribute">xmlns:xsi</span>=<span class="hl-value">"http://www.w3.org/2001/XMLSchema-instance"</span>
     <span class="hl-attribute">xmlns:context</span>=<span class="hl-value">"http://www.springframework.org/schema/context"</span>
     <span class="hl-attribute">xsi:schemaLocation</span>=<span class="hl-value">"http://www.springframework.org/schema/beans
         http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
         http://www.springframework.org/schema/context
         http://www.springframework.org/schema/context/spring-context-3.0.xsd"</span>&gt;

   &lt;<span class="hl-tag">context:component-scan</span> <span class="hl-attribute">base-package</span>=<span class="hl-value">"org.example"</span>/&gt;

&lt;<span class="hl-tag">/beans</span>&gt;</pre><div class="note" style="margin-left: 0.5in; margin-right: 0.5in;"><table border="0" summary="Note"><tr><td rowspan="2" align="center" valign="top" width="25"><img alt="[Note]" src="images/note.gif"></td><th align="left">Note</th></tr><tr><td align="left" valign="top"><p>The scanning of classpath packages requires the presence of
        corresponding directory entries in the classpath. When you build JARs
        with Ant, make sure that you do <span class="emphasis"><em>not</em></span> activate the
        files-only switch of the JAR task.</p></td></tr></table></div><p>Furthermore, the
      <code class="interfacename">AutowiredAnnotationBeanPostProcessor</code> and
      <code class="interfacename">CommonAnnotationBeanPostProcessor</code> are both
      included implicitly when you use the component-scan element. That means
      that the two components are autodetected <span class="emphasis"><em>and</em></span> wired
      together - all without any bean configuration metadata provided in
      XML.</p><div class="note" style="margin-left: 0.5in; margin-right: 0.5in;"><table border="0" summary="Note"><tr><td rowspan="2" align="center" valign="top" width="25"><img alt="[Note]" src="images/note.gif"></td><th align="left">Note</th></tr><tr><td align="left" valign="top"><p>You can disable the registration of
        <code class="interfacename">AutowiredAnnotationBeanPostProcessor</code> and
        <code class="interfacename">CommonAnnotationBeanPostProcessor</code> by
        including the <span class="emphasis"><em>annotation-config</em></span> attribute with a
        value of false.</p></td></tr></table></div></div><div class="section" lang="en"><div class="titlepage"><div><div><h3 class="title"><a name="beans-scanning-filters"></a>4.10.3&nbsp;Using filters to customize scanning</h3></div></div></div><p>By default, classes annotated with
      <code class="interfacename">@Component</code>,
      <code class="interfacename">@Repository</code>,
      <code class="interfacename">@Service</code>,
      <code class="interfacename">@Controller</code>, or a custom annotation that
      itself is annotated with <code class="interfacename">@Component</code> are the
      only detected candidate components. However, you can modify and extend
      this behavior simply by applying custom filters. Add them as
      <span class="emphasis"><em>include-filter</em></span> or <span class="emphasis"><em>exclude-filter</em></span>
      sub-elements of the <code class="literal">component-scan</code> element. Each filter
      element requires the <code class="literal">type</code> and
      <code class="literal">expression</code> attributes. The following table describes
      the filtering options.</p><div class="table"><a name="beans-scanning-filters-tbl"></a><p class="title"><b>Table&nbsp;4.5.&nbsp;Filter Types</b></p><div class="table-contents"><table summary="Filter Types" style="border-collapse: collapse;border-top: 1.0pt solid ; border-bottom: 1.0pt solid ; border-left: 1.0pt solid ; border-right: 1.0pt solid ; "><colgroup><col><col><col></colgroup><thead><tr><th style="border-right: 1.0pt solid ; border-bottom: 1.0pt solid ; ">Filter Type</th><th style="border-right: 1.0pt solid ; border-bottom: 1.0pt solid ; ">Example Expression</th><th style="border-bottom: 1.0pt solid ; ">Description</th></tr></thead><tbody><tr><td style="border-right: 1.0pt solid ; border-bottom: 1.0pt solid ; ">annotation</td><td style="border-right: 1.0pt solid ; border-bottom: 1.0pt solid ; "><code class="literal">org.example.SomeAnnotation</code></td><td style="border-bottom: 1.0pt solid ; ">An annotation to be present at the type level in target
              components.</td></tr><tr><td style="border-right: 1.0pt solid ; border-bottom: 1.0pt solid ; ">assignable</td><td style="border-right: 1.0pt solid ; border-bottom: 1.0pt solid ; "><code class="literal">org.example.SomeClass</code></td><td style="border-bottom: 1.0pt solid ; ">A class (or interface) that the target components are
              assignable to (extend/implement).</td></tr><tr><td style="border-right: 1.0pt solid ; border-bottom: 1.0pt solid ; ">aspectj</td><td style="border-right: 1.0pt solid ; border-bottom: 1.0pt solid ; "><code class="literal">org.example..*Service+</code></td><td style="border-bottom: 1.0pt solid ; ">An AspectJ type expression to be matched by the target
              components.</td></tr><tr><td style="border-right: 1.0pt solid ; border-bottom: 1.0pt solid ; ">regex</td><td style="border-right: 1.0pt solid ; border-bottom: 1.0pt solid ; "><code class="literal">org\.example\.Default.*</code></td><td style="border-bottom: 1.0pt solid ; ">A regex expression to be matched by the target components
              class names.</td></tr><tr><td style="border-right: 1.0pt solid ; ">custom</td><td style="border-right: 1.0pt solid ; "><code class="literal">org.example.MyTypeFilter</code></td><td style="">A custom implementation of the
              <code class="interfacename">org.springframework.core.type
              .TypeFilter</code> interface.</td></tr></tbody></table></div></div><br class="table-break"><p>The following example shows the XML configuration ignoring all
      <code class="interfacename">@Repository</code> annotations and using "stub"
      repositories instead.</p><pre class="programlisting">&lt;<span class="hl-tag">beans</span>&gt;

   &lt;<span class="hl-tag">context:component-scan</span> <span class="hl-attribute">base-package</span>=<span class="hl-value">"org.example"</span>&gt;
      &lt;<span class="hl-tag">context:include-filter</span> <span class="hl-attribute">type</span>=<span class="hl-value">"regex"</span> <span class="hl-attribute">expression</span>=<span class="hl-value">".*Stub.*Repository"</span>/&gt;
      &lt;<span class="hl-tag">context:exclude-filter</span> <span class="hl-attribute">type</span>=<span class="hl-value">"annotation"</span>
                              <span class="hl-attribute">expression</span>=<span class="hl-value">"org.springframework.stereotype.Repository"</span>/&gt;
   &lt;<span class="hl-tag">/context:component-scan</span>&gt;

&lt;<span class="hl-tag">/beans</span>&gt;</pre><div class="note" style="margin-left: 0.5in; margin-right: 0.5in;"><table border="0" summary="Note"><tr><td rowspan="2" align="center" valign="top" width="25"><img alt="[Note]" src="images/note.gif"></td><th align="left">Note</th></tr><tr><td align="left" valign="top"><p>You can also disable the default filters by providing
        <span class="emphasis"><em>use-default-filters="false"</em></span> as an attribute of the
        &lt;component-scan/&gt; element. This will in effect disable automatic
        detection of classes annotated with
        <code class="interfacename">@Component</code>,
        <code class="interfacename">@Repository</code>,
        <code class="interfacename">@Service</code>, or
        <code class="interfacename">@Controller</code>.</p></td></tr></table></div></div><div class="section" lang="en"><div class="titlepage"><div><div><h3 class="title"><a name="beans-factorybeans-annotations"></a>4.10.4&nbsp;Defining bean metadata within components</h3></div></div></div><p>Spring components can also contribute bean definition metadata to the
      container. You do this with the same <code class="literal">@Bean</code> annotation
      used to define bean metadata within <code class="literal">@Configuration</code>
      annotated classes. Here is a simple example:</p><pre class="programlisting">@Component
<span class="hl-keyword">public</span> <span class="hl-keyword">class</span> FactoryMethodComponent {

  @Bean @Qualifier(<span class="hl-string">"public"</span>)
  <span class="hl-keyword">public</span> TestBean publicInstance() {
      <span class="hl-keyword">return</span> <span class="hl-keyword">new</span> TestBean(<span class="hl-string">"publicInstance"</span>);
  }

  <span class="hl-keyword">public</span> <span class="hl-keyword">void</span> doWork() {
      <span class="hl-comment">// Component method implementation omitted</span>
  }
}</pre><p>This class is a Spring component that has application-specific code
      contained in its <code class="methodname">doWork()</code> method. However, it
      also contributes a bean definition that has a factory method referring to
      the method <code class="methodname">publicInstance()</code>. The
      <code class="literal">@Bean</code> annotation identifies the factory method and
      other bean definition properties, such as a qualifier value through the
      <code class="classname">@Qualifier</code> annotation. Other method level
      annotations that can be specified are <code class="literal">@Scope</code>,
      <code class="literal">@Lazy</code>, and custom qualifier annotations. Autowired
      fields and methods are supported as previously discussed, with additional
      support for autowiring of <code class="literal">@Bean</code> methods:</p><pre class="programlisting">@Component
<span class="hl-keyword">public</span> <span class="hl-keyword">class</span> FactoryMethodComponent {

  <span class="hl-keyword">private</span> <span class="hl-keyword">static</span> <span class="hl-keyword">int</span> i;

  @Bean @Qualifier(<span class="hl-string">"public"</span>)
  <span class="hl-keyword">public</span> TestBean publicInstance() {
      <span class="hl-keyword">return</span> <span class="hl-keyword">new</span> TestBean(<span class="hl-string">"publicInstance"</span>);
  }

  <span class="hl-comment">// use of a custom qualifier and autowiring of method parameters</span>

  @Bean
  <span class="hl-keyword">protected</span> TestBean protectedInstance(@Qualifier(<span class="hl-string">"public"</span>) TestBean spouse,
                                       @Value(<span class="hl-string">"#{privateInstance.age}"</span>) String country) {
      TestBean tb = <span class="hl-keyword">new</span> TestBean(<span class="hl-string">"protectedInstance"</span>, 1);
      tb.setSpouse(tb);
      tb.setCountry(country);
      <span class="hl-keyword">return</span> tb;
  }

  @Bean @Scope(BeanDefinition.SCOPE_SINGLETON)
  <span class="hl-keyword">private</span> TestBean privateInstance() {
      <span class="hl-keyword">return</span> <span class="hl-keyword">new</span> TestBean(<span class="hl-string">"privateInstance"</span>, i++);
  }

  @Bean @Scope(value = WebApplicationContext.SCOPE_SESSION,
               proxyMode = ScopedProxyMode.TARGET_CLASS)
  <span class="hl-keyword">public</span> TestBean requestScopedInstance() {
      <span class="hl-keyword">return</span> <span class="hl-keyword">new</span> TestBean(<span class="hl-string">"requestScopedInstance"</span>, 3);
  }
}
</pre><p>The example autowires the <code class="classname">String</code> method
      parameter <code class="literal">country</code> to the value of the
      <code class="literal">Age</code> property on another bean named
      <code class="literal">privateInstance</code>. A Spring Expression Language element
      defines the value of the property through the notation <code class="literal">#{
      &lt;expression&gt; }</code>. For <code class="literal">@Value</code> annotations,
      an expression resolver is preconfigured to look for bean names when
      resolving expression text.</p><p>The <code class="literal">@Bean</code> methods in a Spring component are
      processed differently than their counterparts inside a Spring
      <code class="literal">@Configuration</code> class. The difference is that
      <code class="literal">@Component</code> classes are not enhanced with CGLIB to
      intercept the invocation of methods and fields. CGLIB proxying is the
      means by which invoking methods or fields within
      <code class="literal">@Configuration</code> classes <code class="literal">@Bean</code> methods
      create bean metadata references to collaborating objects. Methods are
      <span class="emphasis"><em>not</em></span> invoked with normal Java semantics. In contrast,
      calling a method or field within a <code class="literal">@Component</code> classes
      <code class="literal">@Bean</code> method <span class="emphasis"><em>has</em></span> standard Java
      semantics.</p></div><div class="section" lang="en"><div class="titlepage"><div><div><h3 class="title"><a name="beans-scanning-name-generator"></a>4.10.5&nbsp;Naming autodetected components</h3></div></div></div><p>When a component is autodetected as part of the scanning process, its
      bean name is generated by the
      <code class="interfacename">BeanNameGenerator</code> strategy known to that
      scanner. By default, any Spring stereotype annotation
      (<code class="interfacename">@Component</code>,
      <code class="interfacename">@Repository</code>,
      <code class="interfacename">@Service</code>, and
      <code class="interfacename">@Controller</code>) that contains a
      <code class="literal">name</code> value will thereby provide that name to the
      corresponding bean definition.</p><div class="note" style="margin-left: 0.5in; margin-right: 0.5in;"><table border="0" summary="Note"><tr><td rowspan="2" align="center" valign="top" width="25"><img alt="[Note]" src="images/note.gif"></td><th align="left">Note</th></tr><tr><td align="left" valign="top"><p>JSR 330's @Named annotation can be used as a means to both detect
        components and to provide them with a name. This behavior is enabled
        automatically if you have the JSR 330 JAR on the classpath.</p></td></tr></table></div><p>If such an annotation contains no <code class="literal">name</code> value or for
      any other detected component (such as those discovered by custom filters),
      the default bean name generator returns the uncapitalized non-qualified
      class name. For example, if the following two components were detected,
      the names would be myMovieLister and movieFinderImpl:</p><pre class="programlisting">@Service(<span class="hl-string">"myMovieLister"</span>)
<span class="hl-keyword">public</span> <span class="hl-keyword">class</span> SimpleMovieLister {
  <span class="hl-comment">// ...</span>
}</pre><pre class="programlisting">@Repository
<span class="hl-keyword">public</span> <span class="hl-keyword">class</span> MovieFinderImpl <span class="hl-keyword">implements</span> MovieFinder {
  <span class="hl-comment">// ...</span>
}</pre><div class="note" style="margin-left: 0.5in; margin-right: 0.5in;"><table border="0" summary="Note"><tr><td rowspan="2" align="center" valign="top" width="25"><img alt="[Note]" src="images/note.gif"></td><th align="left">Note</th></tr><tr><td align="left" valign="top"><p>If you do not want to rely on the default bean-naming strategy, you
        can provide a custom bean-naming strategy. First, implement the <a class="ulink" href="http://static.springframework.org/spring/docs/3.0.x/javadoc-api/org/springframework/beans/factory/support/BeanNameGenerator.html" target="_top"><code class="interfacename">BeanNameGenerator</code></a> interface, and
        be sure to include a default no-arg constructor. Then, provide the
        fully-qualified class name when configuring the scanner:</p></td></tr></table></div><pre class="programlisting">&lt;<span class="hl-tag">beans</span>&gt;

   &lt;<span class="hl-tag">context:component-scan</span> <span class="hl-attribute">base-package</span>=<span class="hl-value">"org.example"</span>
                           <span class="hl-attribute">name-generator</span>=<span class="hl-value">"org.example.MyNameGenerator"</span> /&gt;

&lt;<span class="hl-tag">/beans</span>&gt;</pre><p>As a general rule, consider specifying the name with the annotation
      whenever other components may be making explicit references to it. On the
      other hand, the auto-generated names are adequate whenever the container
      is responsible for wiring.</p></div><div class="section" lang="en"><div class="titlepage"><div><div><h3 class="title"><a name="beans-scanning-scope-resolver"></a>4.10.6&nbsp;Providing a scope for autodetected components</h3></div></div></div><p>As with Spring-managed components in general, the default and most
      common scope for autodetected components is singleton. However, sometimes
      you need other scopes, which Spring 2.5 provides with a new
      <code class="interfacename">@Scope</code> annotation. Simply provide the name
      of the scope within the annotation:</p><pre class="programlisting">@Scope(<span class="hl-string">"prototype"</span>)
@Repository
<span class="hl-keyword">public</span> <span class="hl-keyword">class</span> MovieFinderImpl <span class="hl-keyword">implements</span> MovieFinder {
  <span class="hl-comment">// ...</span>
}</pre><div class="note" style="margin-left: 0.5in; margin-right: 0.5in;"><table border="0" summary="Note"><tr><td rowspan="2" align="center" valign="top" width="25"><img alt="[Note]" src="images/note.gif"></td><th align="left">Note</th></tr><tr><td align="left" valign="top"><p>To provide a custom strategy for scope resolution rather than
        relying on the annotation-based approach, implement the <a class="ulink" href="http://static.springframework.org/spring/docs/3.0.x/javadoc-api/org/springframework/context/annotation/ScopeMetadataResolver.html" target="_top"><code class="interfacename">ScopeMetadataResolver</code></a> interface,
        and be sure to include a default no-arg constructor. Then, provide the
        fully-qualified class name when configuring the scanner:</p></td></tr></table></div><pre class="programlisting">&lt;<span class="hl-tag">beans</span>&gt;

   &lt;<span class="hl-tag">context:component-scan</span> <span class="hl-attribute">base-package</span>=<span class="hl-value">"org.example"</span>
                           <span class="hl-attribute">scope-resolver</span>=<span class="hl-value">"org.example.MyScopeResolver"</span> /&gt;

&lt;<span class="hl-tag">/beans</span>&gt;</pre><p>When using certain non-singleton scopes, it may be necessary to
      generate proxies for the scoped objects. The reasoning is described in
      <a class="xref" href="beans.html#beans-factory-scopes-other-injection" title="4.5.4.5&nbsp;Scoped beans as dependencies">Section&nbsp;4.5.4.5, &#8220;Scoped beans as dependencies&#8221;</a>. For this purpose,
      a <span class="emphasis"><em>scoped-proxy</em></span> attribute is available on the
      component-scan element. The three possible values are: no, interfaces, and
      targetClass. For example, the following configuration will result in
      standard JDK dynamic proxies:</p><pre class="programlisting">&lt;<span class="hl-tag">beans</span>&gt;

   &lt;<span class="hl-tag">context:component-scan</span> <span class="hl-attribute">base-package</span>=<span class="hl-value">"org.example"</span>
                           <span class="hl-attribute">scoped-proxy</span>=<span class="hl-value">"interfaces"</span> /&gt;

&lt;<span class="hl-tag">/beans</span>&gt;</pre></div><div class="section" lang="en"><div class="titlepage"><div><div><h3 class="title"><a name="beans-scanning-qualifiers"></a>4.10.7&nbsp;Providing qualifier metadata with annotations</h3></div></div></div><p>The <code class="interfacename">@Qualifier</code> annotation is discussed
      in <a class="xref" href="beans.html#beans-autowired-annotation-qualifiers" title="4.9.3&nbsp;Fine-tuning annotation-based autowiring with qualifiers">Section&nbsp;4.9.3, &#8220;Fine-tuning annotation-based autowiring with qualifiers&#8221;</a>. The examples
      in that section demonstrate the use of the
      <code class="interfacename">@Qualifier</code> annotation and custom qualifier
      annotations to provide fine-grained control when you resolve autowire
      candidates. Because those examples were based on XML bean definitions, the
      qualifier metadata was provided on the candidate bean definitions using
      the <code class="literal">qualifier</code> or <code class="literal">meta</code> sub-elements
      of the <code class="literal">bean</code> element in the XML. When relying upon
      classpath scanning for autodetection of components, you provide the
      qualifier metadata with type-level annotations on the candidate class. The
      following three examples demonstrate this technique:</p><pre class="programlisting">@Component
@Qualifier(<span class="hl-string">"Action"</span>)
<span class="hl-keyword">public</span> <span class="hl-keyword">class</span> ActionMovieCatalog <span class="hl-keyword">implements</span> MovieCatalog {
  <span class="hl-comment">// ...</span>
}</pre><pre class="programlisting">@Component
@Genre(<span class="hl-string">"Action"</span>)
<span class="hl-keyword">public</span> <span class="hl-keyword">class</span> ActionMovieCatalog <span class="hl-keyword">implements</span> MovieCatalog {
  <span class="hl-comment">// ...</span>
}</pre><pre class="programlisting">@Component
@Offline
<span class="hl-keyword">public</span> <span class="hl-keyword">class</span> CachingMovieCatalog <span class="hl-keyword">implements</span> MovieCatalog {
  <span class="hl-comment">// ...</span>
}</pre><div class="note" style="margin-left: 0.5in; margin-right: 0.5in;"><table border="0" summary="Note"><tr><td rowspan="2" align="center" valign="top" width="25"><img alt="[Note]" src="images/note.gif"></td><th align="left">Note</th></tr><tr><td align="left" valign="top"><p>As with most annotation-based alternatives, keep in mind that the
        annotation metadata is bound to the class definition itself, while the
        use of XML allows for multiple beans <span class="emphasis"><em>of the same
        type</em></span> to provide variations in their qualifier metadata,
        because that metadata is provided per-instance rather than
        per-class.</p></td></tr></table></div></div></div><div class="section" lang="en"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="beans-standard-annotations"></a>4.11&nbsp;Using JSR 330 standard annotations</h2></div></div></div><p>Starting from Spring 3.0, Spring offers support for JSR-330 standard annotations  (Dependency Injection).
  Those annotations are scanned in the same way as the Spring annotations. You just need to have the relevant jars in your classpath.
  </p><div class="note" style="margin-left: 0.5in; margin-right: 0.5in;"><table border="0" summary="Note"><tr><td rowspan="2" align="center" valign="top" width="25"><img alt="[Note]" src="images/note.gif"></td><th align="left">Note</th></tr><tr><td align="left" valign="top">
  If you are using Maven, the <code class="interfacename">javax.inject</code> artifact is available on the standard Maven repository (<a class="ulink" href="http://repo1.maven.org/maven2/javax/inject/javax.inject/1/" target="_top">http://repo1.maven.org/maven2/javax/inject/javax.inject/1/</a>). You just need to add the following dependency to your file pom.xml:
  <pre class="programlisting">
		&lt;<span class="hl-tag">dependency</span>&gt;
			&lt;<span class="hl-tag">groupId</span>&gt;javax.inject&lt;<span class="hl-tag">/groupId</span>&gt;
			&lt;<span class="hl-tag">artifactId</span>&gt;javax.inject&lt;<span class="hl-tag">/artifactId</span>&gt;
			&lt;<span class="hl-tag">version</span>&gt;1&lt;<span class="hl-tag">/version</span>&gt;
		&lt;<span class="hl-tag">/dependency</span>&gt;
  </pre></td></tr></table></div><div class="section" lang="en"><div class="titlepage"><div><div><h3 class="title"><a name="beans-inject-named"></a>4.11.1&nbsp;Dependency Injection with <code class="interfacename">@Inject</code> and <code class="interfacename">@Named</code></h3></div></div></div><p>
    Instead of <code class="interfacename">@Autowired</code>, <code class="interfacename">javax.inject.Inject</code> may be used as follows:
    
    </p><pre class="programlisting">
  <span class="hl-keyword">import</span> javax.inject.Inject;
  <span class="hl-keyword">public</span> <span class="hl-keyword">class</span> SimpleMovieLister {

  <span class="hl-keyword">private</span> MovieFinder movieFinder;

  @Inject
  <span class="hl-keyword">public</span> <span class="hl-keyword">void</span> setMovieFinder(MovieFinder movieFinder) {
      <span class="hl-keyword">this</span>.movieFinder = movieFinder;
  }
  <span class="hl-comment">// ...</span>
}</pre><p>

	As for <code class="interfacename">@Autowired</code>, it is possible to use <code class="interfacename">@Inject</code> at the class-level, field-level, method-level and constructor-argument level.

	If you would like to use a qualified name for the dependency that should be injected, you should use the <code class="interfacename">@Named</code> annotation as follows:
    </p><pre class="programlisting">
  <span class="hl-keyword">import</span> javax.inject.Inject;
  <span class="hl-keyword">import</span> javax.inject.Named;
  
  <span class="hl-keyword">public</span> <span class="hl-keyword">class</span> SimpleMovieLister {

  <span class="hl-keyword">private</span> MovieFinder movieFinder;

  @Inject
  <span class="hl-keyword">public</span> <span class="hl-keyword">void</span> setMovieFinder(@Named(<span class="hl-string">"main"</span>) MovieFinder movieFinder) {
      <span class="hl-keyword">this</span>.movieFinder = movieFinder;
  }
  <span class="hl-comment">// ...</span>
}</pre><p>	
	
    </p></div><div class="section" lang="en"><div class="titlepage"><div><div><h3 class="title"><a name="beans-named"></a>4.11.2&nbsp;<code class="interfacename">@Named</code>: a standard equivalent to the <code class="interfacename">@Component</code> annotation</h3></div></div></div><p>
    Instead of <code class="interfacename">@Component</code>, <code class="interfacename">javax.inject.Named</code> may be used as follows:
        </p><pre class="programlisting">
  <span class="hl-keyword">import</span> javax.inject.Inject;
  <span class="hl-keyword">import</span> javax.inject.Named;
  
  @Named(<span class="hl-string">"movieListener"</span>)
  <span class="hl-keyword">public</span> <span class="hl-keyword">class</span> SimpleMovieLister {

  <span class="hl-keyword">private</span> MovieFinder movieFinder;

  @Inject
  <span class="hl-keyword">public</span> <span class="hl-keyword">void</span> setMovieFinder(MovieFinder movieFinder) {
      <span class="hl-keyword">this</span>.movieFinder = movieFinder;
  }
  <span class="hl-comment">// ...</span>
}</pre><p>	
</p><p>
It is very common to use <code class="interfacename">@Component</code> without specifying a name for the component. <code class="interfacename">@Named</code> can be used in a similar fashion:
    </p><pre class="programlisting">
  <span class="hl-keyword">import</span> javax.inject.Inject;
  <span class="hl-keyword">import</span> javax.inject.Named;
  
  @Named
  <span class="hl-keyword">public</span> <span class="hl-keyword">class</span> SimpleMovieLister {

  <span class="hl-keyword">private</span> MovieFinder movieFinder;

  @Inject
  <span class="hl-keyword">public</span> <span class="hl-keyword">void</span> setMovieFinder(MovieFinder movieFinder) {
      <span class="hl-keyword">this</span>.movieFinder = movieFinder;
  }
  <span class="hl-comment">// ...</span>
}
</pre><p>
</p><p>
When using <code class="interfacename">@Named</code>, it is possible to use component-scanning in the exact same way as when using Spring annotations:
    </p><pre class="programlisting">
    &lt;<span class="hl-tag">beans</span>&gt;
    	&lt;<span class="hl-tag">context:component-scan</span> <span class="hl-attribute">base-package</span>=<span class="hl-value">"org.example"</span>/&gt;
    &lt;<span class="hl-tag">/beans</span>&gt;
</pre><p>	
</p></div><div class="section" lang="en"><div class="titlepage"><div><div><h3 class="title"><a name="beans-standard-annotations-limitations"></a>4.11.3&nbsp;Limitations of the standard approach</h3></div></div></div><p>When working with standard annotations, it is important to know that some significant  features are not available as shown in the table below:</p><div class="table"><a name="annotations-comparison"></a><p class="title"><b>Table&nbsp;4.6.&nbsp;Spring annotations vs standard annotations</b></p><div class="table-contents"><table summary="Spring annotations vs standard annotations" style="border-collapse: collapse;border-top: 1.0pt solid ; border-bottom: 1.0pt solid ; border-left: 1.0pt solid ; border-right: 1.0pt solid ; "><colgroup><col><col><col></colgroup><thead><tr><th style="border-right: 1.0pt solid ; border-bottom: 1.0pt solid ; ">Spring</th><th style="border-right: 1.0pt solid ; border-bottom: 1.0pt solid ; ">javax.inject.*</th><th style="border-bottom: 1.0pt solid ; ">javax.inject restrictions / comments</th></tr></thead><tbody><tr><td style="border-right: 1.0pt solid ; border-bottom: 1.0pt solid ; ">@Autowired</td><td style="border-right: 1.0pt solid ; border-bottom: 1.0pt solid ; ">@Inject</td><td style="border-bottom: 1.0pt solid ; ">@Inject has no 'required' attribute</td></tr><tr><td style="border-right: 1.0pt solid ; border-bottom: 1.0pt solid ; ">@Component</td><td style="border-right: 1.0pt solid ; border-bottom: 1.0pt solid ; ">@Named</td><td style="border-bottom: 1.0pt solid ; ">&nbsp;</td></tr><tr><td style="border-right: 1.0pt solid ; border-bottom: 1.0pt solid ; ">@Scope("singleton")</td><td style="border-right: 1.0pt solid ; border-bottom: 1.0pt solid ; ">@Singleton</td><td style="border-bottom: 1.0pt solid ; ">
                	<p>
                		jsr-330 default scope is like Spring's <code class="interfacename">prototype</code>. However, in order to keep it consistent with Spring's general defaults, a jsr-330 bean declared in the Spring container is a <code class="interfacename">singleton</code> by default. In order to use another scope than <code class="interfacename">singleton</code>, you should use Spring's <code class="interfacename">@Scope</code> annotation.
                	</p>
                	<p>
                		<code class="interfacename">javax.inject</code> also provides a <a class="ulink" href="http://download.oracle.com/javaee/6/api/javax/inject/Scope.html" target="_top">@Scope</a> annotation. Nevertheless, this one only aims to be used for creating your own annotations. 
                	</p>
                </td></tr><tr><td style="border-right: 1.0pt solid ; border-bottom: 1.0pt solid ; ">@Qualifier</td><td style="border-right: 1.0pt solid ; border-bottom: 1.0pt solid ; ">@Named</td><td style="border-bottom: 1.0pt solid ; ">&nbsp;</td></tr><tr><td style="border-right: 1.0pt solid ; border-bottom: 1.0pt solid ; ">@Value</td><td style="border-right: 1.0pt solid ; border-bottom: 1.0pt solid ; ">-</td><td style="border-bottom: 1.0pt solid ; ">no equivalent</td></tr><tr><td style="border-right: 1.0pt solid ; border-bottom: 1.0pt solid ; ">@Required</td><td style="border-right: 1.0pt solid ; border-bottom: 1.0pt solid ; ">-</td><td style="border-bottom: 1.0pt solid ; ">no equivalent</td></tr><tr><td style="border-right: 1.0pt solid ; ">@Lazy</td><td style="border-right: 1.0pt solid ; ">-</td><td style="">no equivalent</td></tr></tbody></table></div></div><p><br class="table-break">
        </p></div></div><div class="section" lang="en"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="beans-java"></a>4.12&nbsp;Java-based container configuration</h2></div></div></div><div class="section" lang="en"><div class="titlepage"><div><div><h3 class="title"><a name="beans-java-basic-concepts"></a>4.12.1&nbsp;Basic concepts: <code class="literal">@Configuration</code> and
      <code class="literal">@Bean</code></h3></div></div></div><p>The central artifact in Spring's new Java-configuration support is the
      <code class="interfacename">@Configuration</code>-annotated class. These
      classes consist principally of
      <code class="interfacename">@Bean</code>-annotated methods that define
      instantiation, configuration, and initialization logic for objects to be
      managed by the Spring IoC container.</p><p>Annotating a class with the
      <code class="interfacename">@Configuration</code> indicates that the class can
      be used by the Spring IoC container as a source of bean definitions. The
      simplest possible <code class="interfacename">@Configuration</code> class
      would read as follows:
      </p><pre class="programlisting">@Configuration
<span class="hl-keyword">public</span> <span class="hl-keyword">class</span> AppConfig {
  @Bean
  <span class="hl-keyword">public</span> MyService myService() {
      <span class="hl-keyword">return</span> <span class="hl-keyword">new</span> MyServiceImpl();
  }
}</pre><p>For those more familiar with Spring <code class="literal">&lt;beans/&gt;</code>
      XML, the <code class="literal">AppConfig</code> class above would be equivalent to:
      </p><pre class="programlisting">&lt;<span class="hl-tag">beans</span>&gt;
  &lt;<span class="hl-tag">bean</span> <span class="hl-attribute">id</span>=<span class="hl-value">"myService"</span> <span class="hl-attribute">class</span>=<span class="hl-value">"com.acme.services.MyServiceImpl"</span>/&gt;
&lt;<span class="hl-tag">/beans</span>&gt;</pre><p>
      As you can see, the <code class="literal">@Bean</code> annotation plays the same
      role as the <code class="literal">&lt;bean/&gt;</code> element. The
      <code class="literal">@Bean</code> annotation will be discussed in depth in the
      sections below. First, however, we'll cover the various ways of creating a
      spring container using Java-based configuration.</p></div><div class="section" lang="en"><div class="titlepage"><div><div><h3 class="title"><a name="beans-java-instantiating-container"></a>4.12.2&nbsp;Instantiating the Spring container using
      <code class="literal">AnnotationConfigApplicationContext</code></h3></div></div></div><p>The sections below document Spring's
      <code class="literal">AnnotationConfigApplicationContext</code>, new in Spring 3.0.
      This versatile <code class="literal">ApplicationContext</code> implementation is
      capable of accepting not only <code class="literal">@Configuration</code> classes as
      input, but also plain <code class="literal">@Component</code> classes and classes
      annotated with JSR-330 metadata.</p><p>When <code class="literal">@Configuration</code> classes are provided as input,
      the <code class="literal">@Configuration</code> class itself is registered as a bean
      definition, and all declared <code class="literal">@Bean</code> methods within the
      class are also registered as bean definitions.</p><p>When <code class="literal">@Component</code> and JSR-330 classes are provided,
      they are registered as bean definitions, and it is assumed that DI
      metadata such as <code class="literal">@Autowired</code> or
      <code class="literal">@Inject</code> are used within those classes where
      necessary.</p><div class="section" lang="en"><div class="titlepage"><div><div><h4 class="title"><a name="beans-java-instantiating-container-contstructor"></a>4.12.2.1&nbsp;Simple construction</h4></div></div></div><p>In much the same way that Spring XML files are used as input when
        instantiating a <code class="literal">ClassPathXmlApplicationContext</code>,
        <code class="literal">@Configuration</code> classes may be used as input when
        instantiating an <code class="literal">AnnotationConfigApplicationContext</code>.
        This allows for completely XML-free usage of the Spring container:
        </p><pre class="programlisting"><span class="hl-keyword">public</span> <span class="hl-keyword">static</span> <span class="hl-keyword">void</span> main(String[] args) {
  ApplicationContext ctx = <span class="hl-keyword">new</span> AnnotationConfigApplicationContext(AppConfig.<span class="hl-keyword">class</span>);
  MyService myService = ctx.getBean(MyService.<span class="hl-keyword">class</span>);
  myService.doStuff();
}</pre><p>
        As mentioned above,
        <code class="literal">AnnotationConfigApplicationContext</code> is not limited to
        working only with <code class="literal">@Configuration</code> classes. Any
        <code class="literal">@Component</code> or JSR-330 annotated class may be supplied
        as input to the constructor. For example:
        </p><pre class="programlisting"><span class="hl-keyword">public</span> <span class="hl-keyword">static</span> <span class="hl-keyword">void</span> main(String[] args) {
  ApplicationContext ctx = <span class="hl-keyword">new</span> AnnotationConfigApplicationContext(MyServiceImpl.<span class="hl-keyword">class</span>, Dependency1.<span class="hl-keyword">class</span>, Dependency2.<span class="hl-keyword">class</span>);
  MyService myService = ctx.getBean(MyService.<span class="hl-keyword">class</span>);
  myService.doStuff();
}</pre><p>
        The above assumes that <code class="literal">MyServiceImpl</code>,
        <code class="literal">Dependency1</code> and <code class="literal">Dependency2</code> use
        Spring dependency injection annotations such as
        <code class="literal">@Autowired</code>.</p></div><div class="section" lang="en"><div class="titlepage"><div><div><h4 class="title"><a name="beans-java-instantiating-container-register"></a>4.12.2.2&nbsp;Building the container programmatically using
        <code class="literal">register(Class&lt;?&gt;...)</code></h4></div></div></div><p>An <code class="literal">AnnotationConfigApplicationContext</code> may be
        instantiated using a no-arg constructor and then configured using the
        <code class="literal">register()</code> method. This approach is particularly
        useful when programmatically building an
        <code class="literal">AnnotationConfigApplicationContext</code>.
        </p><pre class="programlisting"><span class="hl-keyword">public</span> <span class="hl-keyword">static</span> <span class="hl-keyword">void</span> main(String[] args) {
  AnnotationConfigApplicationContext ctx = <span class="hl-keyword">new</span> AnnotationConfigApplicationContext();
  ctx.register(AppConfig.<span class="hl-keyword">class</span>, OtherConfig.<span class="hl-keyword">class</span>);
  ctx.register(AdditionalConfig.<span class="hl-keyword">class</span>);
  ctx.refresh();
  MyService myService = ctx.getBean(MyService.<span class="hl-keyword">class</span>);
  myService.doStuff();
}</pre></div><div class="section" lang="en"><div class="titlepage"><div><div><h4 class="title"><a name="beans-java-instantiating-container-scan"></a>4.12.2.3&nbsp;Enabling component scanning with
        <code class="literal">scan(String...)</code></h4></div></div></div><p>Experienced Spring users will be familiar with the following
        commonly-used XML declaration from Spring's <code class="literal">context:</code>
        namespace
        </p><pre class="programlisting">&lt;<span class="hl-tag">beans</span>&gt;
  &lt;<span class="hl-tag">context:component-scan</span> <span class="hl-attribute">base-package</span>=<span class="hl-value">"com.acme"</span>/&gt;
&lt;<span class="hl-tag">/beans</span>&gt;</pre><p>
        In the example above, the <code class="literal">com.acme</code> package will be
        scanned, looking for any <code class="literal">@Component</code>-annotated
        classes, and those classes will be registered as Spring bean definitions
        within the container.
        <code class="literal">AnnotationConfigApplicationContext</code> exposes the
        <code class="literal">scan(String...)</code> method to allow for the same
        component-scanning
        functionality:</p><pre class="programlisting"><span class="hl-keyword">public</span> <span class="hl-keyword">static</span> <span class="hl-keyword">void</span> main(String[] args) {
  AnnotationConfigApplicationContext ctx = <span class="hl-keyword">new</span> AnnotationConfigApplicationContext();
  ctx.scan(<span class="hl-string">"com.acme"</span>);
  ctx.refresh();
  MyService myService = ctx.getBean(MyService.<span class="hl-keyword">class</span>);
}</pre><div class="note" style="margin-left: 0.5in; margin-right: 0.5in;"><table border="0" summary="Note"><tr><td rowspan="2" align="center" valign="top" width="25"><img alt="[Note]" src="images/note.gif"></td><th align="left">Note</th></tr><tr><td align="left" valign="top"><p>Remember that <code class="literal">@Configuration</code> classes are
          meta-annotated with <code class="literal">@Component</code>, so they are
          candidates for component-scanning! In the example above, assuming that
          <code class="literal">AppConfig</code> is declared within the
          <code class="literal">com.acme</code> package (or any package underneath), it
          will be picked up during the call to <code class="literal">scan()</code>, and
          upon <code class="literal">refresh()</code> all its <code class="literal">@Bean</code>
          methods will be processed and registered as bean definitions within
          the container.</p></td></tr></table></div></div><div class="section" lang="en"><div class="titlepage"><div><div><h4 class="title"><a name="beans-java-instantiating-container-web"></a>4.12.2.4&nbsp;Support for web applications with
        <code class="literal">AnnotationConfigWebApplicationContext</code></h4></div></div></div><p>A <code class="literal">WebApplicationContext</code> variant of
        <code class="literal">AnnotationConfigApplicationContext</code> is available with
        <code class="literal">AnnotationConfigWebApplicationContext</code>. This
        implementation may be used when configuring the Spring
        <code class="literal">ContextLoaderListener</code> servlet listener, Spring MVC
        <code class="literal">DispatcherServlet</code>, etc. What follows is a
        <code class="literal">web.xml</code> snippet that configures a typical Spring MVC
        web application. Note the use of the <code class="literal">contextClass</code>
        context-param and init-param:
        </p><pre class="programlisting">
&lt;<span class="hl-tag">web-app</span>&gt;
  &lt;<span class="hl-comment">!-- Configure ContextLoaderListener to use AnnotationConfigWebApplicationContext
       instead of the default XmlWebApplicationContext --</span>&gt;
  &lt;<span class="hl-tag">context-param</span>&gt;
      &lt;<span class="hl-tag">param-name</span>&gt;contextClass&lt;<span class="hl-tag">/param-name</span>&gt;
      &lt;<span class="hl-tag">param-value</span>&gt;
          org.springframework.web.context.support.AnnotationConfigWebApplicationContext
      &lt;<span class="hl-tag">/param-value</span>&gt;
  &lt;<span class="hl-tag">/context-param</span>&gt;

  &lt;<span class="hl-comment">!-- Configuration locations must consist of one or more comma- or space-delimited
       fully-qualified @Configuration classes. Fully-qualified packages may also be
       specified for component-scanning --</span>&gt;
  &lt;<span class="hl-tag">context-param</span>&gt;
      &lt;<span class="hl-tag">param-name</span>&gt;contextConfigLocation&lt;<span class="hl-tag">/param-name</span>&gt;
      &lt;<span class="hl-tag">param-value</span>&gt;com.acme.AppConfig&lt;<span class="hl-tag">/param-value</span>&gt;
  &lt;<span class="hl-tag">/context-param</span>&gt;

  &lt;<span class="hl-comment">!-- Bootstrap the root application context as usual using ContextLoaderListener --</span>&gt;
  &lt;<span class="hl-tag">listener</span>&gt;
      &lt;<span class="hl-tag">listener-class</span>&gt;org.springframework.web.context.ContextLoaderListener&lt;<span class="hl-tag">/listener-class</span>&gt;
  &lt;<span class="hl-tag">/listener</span>&gt;

  &lt;<span class="hl-comment">!-- Declare a Spring MVC DispatcherServlet as usual --</span>&gt;
  &lt;<span class="hl-tag">servlet</span>&gt;
      &lt;<span class="hl-tag">servlet-name</span>&gt;dispatcher&lt;<span class="hl-tag">/servlet-name</span>&gt;
      &lt;<span class="hl-tag">servlet-class</span>&gt;org.springframework.web.servlet.DispatcherServlet&lt;<span class="hl-tag">/servlet-class</span>&gt;
      &lt;<span class="hl-comment">!-- Configure DispatcherServlet to use AnnotationConfigWebApplicationContext
           instead of the default XmlWebApplicationContext --</span>&gt;
      &lt;<span class="hl-tag">init-param</span>&gt;
          &lt;<span class="hl-tag">param-name</span>&gt;contextClass&lt;<span class="hl-tag">/param-name</span>&gt;
          &lt;<span class="hl-tag">param-value</span>&gt;
              org.springframework.web.context.support.AnnotationConfigWebApplicationContext
          &lt;<span class="hl-tag">/param-value</span>&gt;
      &lt;<span class="hl-tag">/init-param</span>&gt;
      &lt;<span class="hl-comment">!-- Again, config locations must consist of one or more comma- or space-delimited
           and fully-qualified @Configuration classes --</span>&gt;
      &lt;<span class="hl-tag">init-param</span>&gt;
          &lt;<span class="hl-tag">param-name</span>&gt;contextConfigLocation&lt;<span class="hl-tag">/param-name</span>&gt;
          &lt;<span class="hl-tag">param-value</span>&gt;com.acme.web.MvcConfig&lt;<span class="hl-tag">/param-value</span>&gt;
      &lt;<span class="hl-tag">/init-param</span>&gt;
  &lt;<span class="hl-tag">/servlet</span>&gt;

  &lt;<span class="hl-comment">!-- map all requests for /main/* to the dispatcher servlet --</span>&gt;
  &lt;<span class="hl-tag">servlet-mapping</span>&gt;
      &lt;<span class="hl-tag">servlet-name</span>&gt;dispatcher&lt;<span class="hl-tag">/servlet-name</span>&gt;
      &lt;<span class="hl-tag">url-pattern</span>&gt;/main/*&lt;<span class="hl-tag">/url-pattern</span>&gt;
  &lt;<span class="hl-tag">/servlet-mapping</span>&gt;
&lt;<span class="hl-tag">/web-app</span>&gt;</pre></div></div><div class="section" lang="en"><div class="titlepage"><div><div><h3 class="title"><a name="beans-java-composing-configuration-classes"></a>4.12.3&nbsp;Composing Java-based configurations</h3></div></div></div><div class="section" lang="en"><div class="titlepage"><div><div><h4 class="title"><a name="beans-java-using-import"></a>4.12.3.1&nbsp;Using the <code class="literal">@Import</code> annotation</h4></div></div></div><p>Much as the <code class="literal">&lt;import/&gt;</code> element is used
        within Spring XML files to aid in modularizing configurations, the
        <code class="literal">@Import</code> annotation allows for loading
        <code class="literal">@Bean</code> definitions from another configuration
        class:</p><pre class="programlisting">@Configuration
<span class="hl-keyword">public</span> <span class="hl-keyword">class</span> ConfigA {
  <span class="hl-keyword">public</span> @Bean A a() { <span class="hl-keyword">return</span> <span class="hl-keyword">new</span> A(); }
}

@Configuration
@Import(ConfigA.<span class="hl-keyword">class</span>)
<span class="hl-keyword">public</span> <span class="hl-keyword">class</span> ConfigB {
  <span class="hl-keyword">public</span> @Bean B b() { <span class="hl-keyword">return</span> <span class="hl-keyword">new</span> B(); }
}</pre><p>
        Now, rather than needing to specify both
        <code class="literal">ConfigA.class</code> and <code class="literal">ConfigB.class</code>
        when instantiating the context, only <code class="literal">ConfigB</code> needs to
        be supplied
        explicitly:</p><pre class="programlisting"><span class="hl-keyword">public</span> <span class="hl-keyword">static</span> <span class="hl-keyword">void</span> main(String[] args) {
  ApplicationContext ctx = <span class="hl-keyword">new</span> AnnotationConfigApplicationContext(ConfigB.<span class="hl-keyword">class</span>);

  <span class="hl-comment">// now both beans A and B will be available...</span>
  A a = ctx.getBean(A.<span class="hl-keyword">class</span>);
  B b = ctx.getBean(B.<span class="hl-keyword">class</span>);
}</pre><p>
        This approach simplifies container instantiation, as only one class
        needs to be dealt with, rather than requiring the developer to remember
        a potentially large number of <code class="literal">@Configuration</code> classes
        during construction.</p><div class="section" lang="en"><div class="titlepage"><div><div><h5 class="title"><a name="beans-java-injecting-imported-beans"></a>Injecting dependencies on imported <code class="literal">@Bean</code>
          definitions</h5></div></div></div><p>The example above works, but is simplistic. In most practical
          scenarios, beans will have dependencies on one another across
          configuration classes. When using XML, this is not an issue, per se,
          because there is no compiler involved, and one can simply declare
          <code class="literal">ref="someBean"</code> and trust that Spring will work it
          out during container initialization. Of course, when using
          <code class="literal">@Configuration</code> classes, the Java compiler places
          constraints on the configuration model, in that references to other
          beans must be valid Java syntax.</p><p>Fortunately, solving this problem is simple. Remember that
          <code class="literal">@Configuration</code> classes are ultimately just another
          bean in the container - this means that they can take advantage of
          <code class="literal">@Autowired</code> injection metadata just like any other
          bean!</p><p>Let's consider a more real-world scenario with several
          <code class="literal">@Configuration</code> classes, each depending on beans
          declared in the
          others:</p><pre class="programlisting">@Configuration
<span class="hl-keyword">public</span> <span class="hl-keyword">class</span> ServiceConfig {
  <span class="hl-keyword">private</span> @Autowired AccountRepository accountRepository;

  <span class="hl-keyword">public</span> @Bean TransferService transferService() {
      <span class="hl-keyword">return</span> <span class="hl-keyword">new</span> TransferServiceImpl(accountRepository);
  }
}

@Configuration
<span class="hl-keyword">public</span> <span class="hl-keyword">class</span> RepositoryConfig {
  <span class="hl-keyword">private</span> @Autowired DataSource dataSource;

  <span class="hl-keyword">public</span> @Bean AccountRepository accountRepository() {
      <span class="hl-keyword">return</span> <span class="hl-keyword">new</span> JdbcAccountRepository(dataSource);
  }
}

@Configuration
@Import({ServiceConfig.<span class="hl-keyword">class</span>, RepositoryConfig.<span class="hl-keyword">class</span>})
<span class="hl-keyword">public</span> <span class="hl-keyword">class</span> SystemTestConfig {
  <span class="hl-keyword">public</span> @Bean DataSource dataSource() { <span class="hl-comment">/* return new DataSource */</span> }
}

<span class="hl-keyword">public</span> <span class="hl-keyword">static</span> <span class="hl-keyword">void</span> main(String[] args) {
  ApplicationContext ctx = <span class="hl-keyword">new</span> AnnotationConfigApplicationContext(SystemTestConfig.<span class="hl-keyword">class</span>);
  <span class="hl-comment">// everything wires up across configuration classes...</span>
  TransferService transferService = ctx.getBean(TransferService.<span class="hl-keyword">class</span>);
  transferService.transfer(100.00, <span class="hl-string">"A123"</span>, <span class="hl-string">"C456"</span>);
}</pre><div class="section" lang="en"><div class="titlepage"><div><div><h6 class="title"><a name="beans-java-injecting-imported-beans-fq"></a>Fully-qualifying imported beans for ease of navigation</h6></div></div></div><p>In the scenario above, using <code class="literal">@Autowired</code> works
            well and provides the desired modularity, but determining exactly
            where the autowired bean definitions are declared is still somewhat
            ambiguous. For example, as a developer looking at
            <code class="literal">ServiceConfig</code>, how do you know exactly where the
            <code class="literal">@Autowired AccountRepository</code> bean is declared?
            It's not explicit in the code, and this may be just fine. Remember
            that the <a class="ulink" href="http://www.springsource.com/products/sts" target="_top">SpringSource Tool Suite</a> provides tooling that can render
            graphs showing how everything is wired up - that may be all you
            need. Also, your Java IDE can easily find all declarations and uses
            of the <code class="literal">AccountRepository</code> type, and will quickly
            show you the location of <code class="literal">@Bean</code> methods that
            return that type.</p><p>In cases where this ambiguity is not acceptable and you wish to
            have direct navigation from within your IDE from one
            <code class="literal">@Configuration</code> class to another, consider
            autowiring the configuration classes themselves:
            </p><pre class="programlisting">@Configuration
<span class="hl-keyword">public</span> <span class="hl-keyword">class</span> ServiceConfig {
  <span class="hl-keyword">private</span> @Autowired RepositoryConfig repositoryConfig;

  <span class="hl-keyword">public</span> @Bean TransferService transferService() {
      <span class="hl-comment">// navigate 'through' the config class to the @Bean method!</span>
      <span class="hl-keyword">return</span> <span class="hl-keyword">new</span> TransferServiceImpl(repositoryConfig.accountRepository());
  }
}</pre><p>
            In the situation above, it is completely explicit where
            <code class="literal">AccountRepository</code> is defined. However,
            <code class="literal">ServiceConfig</code> is now tightly coupled to
            <code class="literal">RepositoryConfig</code>; that's the tradeoff. This tight
            coupling can be somewhat mitigated by using interface-based or
            abstract class-based <code class="literal">@Configuration</code> classes.
            Consider the following:
            </p><pre class="programlisting">@Configuration
<span class="hl-keyword">public</span> <span class="hl-keyword">class</span> ServiceConfig {
  <span class="hl-keyword">private</span> @Autowired RepositoryConfig repositoryConfig;

  <span class="hl-keyword">public</span> @Bean TransferService transferService() {
      <span class="hl-keyword">return</span> <span class="hl-keyword">new</span> TransferServiceImpl(repositoryConfig.accountRepository());
  }
}

@Configuration
<span class="hl-keyword">public</span> <span class="hl-keyword">interface</span> RepositoryConfig {
  @Bean AccountRepository accountRepository();
}

@Configuration
<span class="hl-keyword">public</span> <span class="hl-keyword">class</span> DefaultRepositoryConfig <span class="hl-keyword">implements</span> RepositoryConfig {
  <span class="hl-keyword">public</span> @Bean AccountRepository accountRepository() {
      <span class="hl-keyword">return</span> <span class="hl-keyword">new</span> JdbcAccountRepository(...);
  }
}

@Configuration
@Import({ServiceConfig.<span class="hl-keyword">class</span>, DefaultRepositoryConfig.<span class="hl-keyword">class</span>}) <span class="hl-comment">// import the concrete config!</span>
<span class="hl-keyword">public</span> <span class="hl-keyword">class</span> SystemTestConfig {
  <span class="hl-keyword">public</span> @Bean DataSource dataSource() { <span class="hl-comment">/* return DataSource */</span> }
}

<span class="hl-keyword">public</span> <span class="hl-keyword">static</span> <span class="hl-keyword">void</span> main(String[] args) {
  ApplicationContext ctx = <span class="hl-keyword">new</span> AnnotationConfigApplicationContext(SystemTestConfig.<span class="hl-keyword">class</span>);
  TransferService transferService = ctx.getBean(TransferService.<span class="hl-keyword">class</span>);
  transferService.transfer(100.00, <span class="hl-string">"A123"</span>, <span class="hl-string">"C456"</span>);
}</pre><p>
            Now <code class="literal">ServiceConfig</code> is loosely coupled with respect
            to the concrete <code class="literal">DefaultRepositoryConfig</code>, and
            built-in IDE tooling is still useful: it will be easy for the
            developer to get a type hierarchy of
            <code class="literal">RepositoryConfig</code> implementations. In this way,
            navigating <code class="literal">@Configuration</code> classes and their
            dependencies becomes no different than the usual process of
            navigating interface-based code.</p></div></div></div><div class="section" lang="en"><div class="titlepage"><div><div><h4 class="title"><a name="beans-java-combining"></a>4.12.3.2&nbsp;Combining Java and XML configuration</h4></div></div></div><p>Spring's <code class="literal">@Configuration</code> class support does not
        aim to be a 100% complete replacement for Spring XML. Some facilities
        such as Spring XML namespaces remain an ideal way to configure the
        container. In cases where XML is convenient or necessary, you have a
        choice: either instantiate the container in an "XML-centric" way using,
        for example, <code class="literal">ClassPathXmlApplicationContext</code>, or in a
        "Java-centric" fashion using
        <code class="literal">AnnotationConfigApplicationContext</code> and the
        <code class="literal">@ImportResource</code> annotation to import XML as
        needed.</p><div class="section" lang="en"><div class="titlepage"><div><div><h5 class="title"><a name="beans-java-combining-xml-centric"></a>XML-centric use of <code class="literal">@Configuration</code>
          classes</h5></div></div></div><p>It may be preferable to bootstrap the Spring container from XML
          and include <code class="literal">@Configuration</code> classes in an ad-hoc
          fashion. For example, in a large existing codebase that uses Spring
          XML, it will be easier to create <code class="literal">@Configuration</code>
          classes on an as-needed basis and include them from the existing XML
          files. Below you'll find the options for using
          <code class="literal">@Configuration</code> classes in this kind of
          "XML-centric" situation.</p><div class="section" lang="en"><div class="titlepage"><div><div><h6 class="title"><a name="beans-java-combining-xml-centric-declare-as-bean"></a>Declaring <code class="literal">@Configuration</code> classes as plain
            Spring <code class="literal">&lt;bean/&gt;</code> elements</h6></div></div></div><p>Remember that <code class="literal">@Configuration</code> classes are
            ultimately just bean definitions in the container. In this example,
            we create a <code class="literal">@Configuration</code> class named
            <code class="literal">AppConfig</code> and include it within
            <code class="literal">system-test-config.xml</code> as a
            <code class="literal">&lt;bean/&gt;</code>definition. Because
            <code class="literal">&lt;context:annotation-config/&gt;</code> is switched
            on, the container will recognize the
            <code class="literal">@Configuration</code> annotation, and process the
            <code class="literal">@Bean</code> methods declared in
            <code class="literal">AppConfig</code>
            properly.</p><pre class="programlisting">@Configuration
<span class="hl-keyword">public</span> <span class="hl-keyword">class</span> AppConfig {
  <span class="hl-keyword">private</span> @Autowired DataSource dataSource;

  <span class="hl-keyword">public</span> @Bean AccountRepository accountRepository() {
      <span class="hl-keyword">return</span> <span class="hl-keyword">new</span> JdbcAccountRepository(dataSource);
  }

  <span class="hl-keyword">public</span> @Bean TransferService transferService() {
      <span class="hl-keyword">return</span> <span class="hl-keyword">new</span> TransferService(accountRepository());
  }
}</pre><p>
            </p><pre class="programlisting">system-test-config.xml
&lt;<span class="hl-tag">beans</span>&gt;
  &lt;<span class="hl-comment">!-- enable processing of annotations such as @Autowired and @Configuration --</span>&gt;
  &lt;<span class="hl-tag">context:annotation-config</span>/&gt;
  &lt;<span class="hl-tag">context:property-placeholder</span> <span class="hl-attribute">location</span>=<span class="hl-value">"classpath:/com/acme/jdbc.properties"</span>/&gt;

  &lt;<span class="hl-tag">bean</span> <span class="hl-attribute">class</span>=<span class="hl-value">"com.acme.AppConfig"</span>/&gt;

  &lt;<span class="hl-tag">bean</span> <span class="hl-attribute">class</span>=<span class="hl-value">"org.springframework.jdbc.datasource.DriverManagerDataSource"</span>&gt;
      &lt;<span class="hl-tag">property</span> <span class="hl-attribute">name</span>=<span class="hl-value">"url"</span> <span class="hl-attribute">value</span>=<span class="hl-value">"${jdbc.url}"</span>/&gt;
      &lt;<span class="hl-tag">property</span> <span class="hl-attribute">name</span>=<span class="hl-value">"username"</span> <span class="hl-attribute">value</span>=<span class="hl-value">"${jdbc.username}"</span>/&gt;
      &lt;<span class="hl-tag">property</span> <span class="hl-attribute">name</span>=<span class="hl-value">"password"</span> <span class="hl-attribute">value</span>=<span class="hl-value">"${jdbc.password}"</span>/&gt;
  &lt;<span class="hl-tag">/bean</span>&gt;
&lt;<span class="hl-tag">/beans</span>&gt;</pre><p>
            </p><pre class="programlisting"><em class="lineannotation"><span class="lineannotation">jdbc.properties</span></em>
jdbc.url=jdbc:hsqldb:hsql://localhost/xdb
jdbc.username=sa
jdbc.password=</pre><p>
            </p><pre class="programlisting"><span class="hl-keyword">public</span> <span class="hl-keyword">static</span> <span class="hl-keyword">void</span> main(String[] args) {
  ApplicationContext ctx = <span class="hl-keyword">new</span> ClassPathXmlApplicationContext(<span class="hl-string">"classpath:/com/acme/system-test-config.xml"</span>);
  TransferService transferService = ctx.getBean(TransferService.<span class="hl-keyword">class</span>);
  <span class="hl-comment">// ...</span>
}</pre><div class="note" style="margin-left: 0.5in; margin-right: 0.5in;"><table border="0" summary="Note"><tr><td rowspan="2" align="center" valign="top" width="25"><img alt="[Note]" src="images/note.gif"></td><th align="left">Note</th></tr><tr><td align="left" valign="top"><p>In <code class="literal">system-test-config.xml</code> above, the
              <code class="literal">AppConfig&lt;bean/&gt;</code> does not declare an
              <code class="literal">id</code> element. While it would be acceptable to do
              so, it is unnecessary given that no other bean will ever refer to
              it, and it is unlikely that it will be explicitly fetched from the
              container by name. Likewise with the <code class="literal">DataSource</code>
              bean - it is only ever autowired by type, so an explicit bean id
              is not strictly required.</p></td></tr></table></div></div><div class="section" lang="en"><div class="titlepage"><div><div><h6 class="title"><a name="beans-java-combining-xml-centric-component-scan"></a>Using <code class="literal">&lt;context:component-scan/&gt;</code> to
            pick up <code class="literal">@Configuration</code> classes</h6></div></div></div><p>Because <code class="literal">@Configuration</code> is meta-annotated with
            <code class="literal">@Component</code>,
            <code class="literal">@Configuration</code>-annotated classes are
            automatically candidates for component scanning. Using the same
            scenario as above, we can redefine
            <code class="literal">system-test-config.xml</code> to take advantage of
            component-scanning. Note that in this case, we don't need to
            explicitly declare
            <code class="literal">&lt;context:annotation-config/&gt;</code>, because
            <code class="literal">&lt;context:component-scan/&gt;</code> enables all the
            same
            functionality.</p><pre class="programlisting">system-test-config.xml
&lt;<span class="hl-tag">beans</span>&gt;
  &lt;<span class="hl-comment">!-- picks up and registers AppConfig as a bean definition --</span>&gt;
  &lt;<span class="hl-tag">context:component-scan</span> <span class="hl-attribute">base-package</span>=<span class="hl-value">"com.acme"</span>/&gt;
  &lt;<span class="hl-tag">context:property-placeholder</span> <span class="hl-attribute">location</span>=<span class="hl-value">"classpath:/com/acme/jdbc.properties"</span>/&gt;

  &lt;<span class="hl-tag">bean</span> <span class="hl-attribute">class</span>=<span class="hl-value">"org.springframework.jdbc.datasource.DriverManagerDataSource"</span>&gt;
      &lt;<span class="hl-tag">property</span> <span class="hl-attribute">name</span>=<span class="hl-value">"url"</span> <span class="hl-attribute">value</span>=<span class="hl-value">"${jdbc.url}"</span>/&gt;
      &lt;<span class="hl-tag">property</span> <span class="hl-attribute">name</span>=<span class="hl-value">"username"</span> <span class="hl-attribute">value</span>=<span class="hl-value">"${jdbc.username}"</span>/&gt;
      &lt;<span class="hl-tag">property</span> <span class="hl-attribute">name</span>=<span class="hl-value">"password"</span> <span class="hl-attribute">value</span>=<span class="hl-value">"${jdbc.password}"</span>/&gt;
  &lt;<span class="hl-tag">/bean</span>&gt;
&lt;<span class="hl-tag">/beans</span>&gt;</pre></div></div><div class="section" lang="en"><div class="titlepage"><div><div><h5 class="title"><a name="beans-java-combining-java-centric"></a><code class="literal">@Configuration</code> class-centric use of XML with
          <code class="literal">@ImportResource</code></h5></div></div></div><p>In applications where <code class="literal">@Configuration</code> classes
          are the primary mechanism for configuring the container, it will still
          likely be necessary to use at least some XML. In these scenarios,
          simply use <code class="literal">@ImportResource</code> and define only as much
          XML as is needed. Doing so achieves a "Java-centric" approach to
          configuring the container and keeps XML to a bare minimum.
          </p><pre class="programlisting">@Configuration
@ImportResource(<span class="hl-string">"classpath:/com/acme/properties-config.xml"</span>)
<span class="hl-keyword">public</span> <span class="hl-keyword">class</span> AppConfig {
  <span class="hl-keyword">private</span> @Value(<span class="hl-string">"${jdbc.url}"</span>) String url;
  <span class="hl-keyword">private</span> @Value(<span class="hl-string">"${jdbc.username}"</span>) String username;
  <span class="hl-keyword">private</span> @Value(<span class="hl-string">"${jdbc.password}"</span>) String password;

  <span class="hl-keyword">public</span> @Bean DataSource dataSource() {
      <span class="hl-keyword">return</span> <span class="hl-keyword">new</span> DriverManagerDataSource(url, username, password);
  }
}</pre><p>
          </p><pre class="programlisting">properties-config.xml
&lt;<span class="hl-tag">beans</span>&gt;
  &lt;<span class="hl-tag">context:property-placeholder</span> <span class="hl-attribute">location</span>=<span class="hl-value">"classpath:/com/acme/jdbc.properties"</span>/&gt;
&lt;<span class="hl-tag">/beans</span>&gt;</pre><p>
          </p><pre class="programlisting"><em class="lineannotation"><span class="lineannotation">jdbc.properties</span></em>
jdbc.url=jdbc:hsqldb:hsql://localhost/xdb
jdbc.username=sa
jdbc.password=</pre><p>
          </p><pre class="programlisting"><span class="hl-keyword">public</span> <span class="hl-keyword">static</span> <span class="hl-keyword">void</span> main(String[] args) {
  ApplicationContext ctx = <span class="hl-keyword">new</span> AnnotationConfigApplicationContext(AppConfig.<span class="hl-keyword">class</span>);
  TransferService transferService = ctx.getBean(TransferService.<span class="hl-keyword">class</span>);
  <span class="hl-comment">// ...</span>
}</pre></div></div></div><div class="section" lang="en"><div class="titlepage"><div><div><h3 class="title"><a name="beans-java-bean-annotation"></a>4.12.4&nbsp;Using the <code class="interfacename">@Bean</code> annotation</h3></div></div></div><p><code class="interfacename">@Bean</code> is a method-level annotation and
      a direct analog of the XML <code class="code">&lt;bean/&gt;</code> element. The
      annotation supports some of the attributes offered by
      <code class="code">&lt;bean/&gt;</code>, such as: <code class="code"><a class="link" href="beans.html#beans-factory-lifecycle-initializingbean" title="4.6.1.1&nbsp;Initialization callbacks">init-method</a></code>, <code class="code"><a class="link" href="beans.html#beans-factory-lifecycle-disposablebean" title="4.6.1.2&nbsp;Destruction callbacks">destroy-method</a></code>, <code class="code"><a class="link" href="beans.html#beans-factory-autowire" title="4.4.5&nbsp;Autowiring collaborators">autowiring</a></code> and
      <code class="code">name</code>.</p><p>You can use the <code class="interfacename">@Bean</code> annotation in a
      <code class="interfacename">@Configuration</code>-annotated or in a
      <code class="interfacename">@Component</code>-annotated class.</p><div class="section" lang="en"><div class="titlepage"><div><div><h4 class="title"><a name="beans-java-declaring-a-bean"></a>4.12.4.1&nbsp;Declaring a bean</h4></div></div></div><p>To declare a bean, simply annotate a method with the
        <code class="interfacename">@Bean</code> annotation. You use this method to
        register a bean definition within an <code class="code">ApplicationContext</code> of
        the type specified as the method's return value. By default, the bean
        name will be the same as the method name. The following is a simple
        example of a <code class="interfacename">@Bean</code> method declaration:
        </p><pre class="programlisting">@Configuration
<span class="hl-keyword">public</span> <span class="hl-keyword">class</span> AppConfig {

  @Bean
  <span class="hl-keyword">public</span> TransferService transferService() {
      <span class="hl-keyword">return</span> <span class="hl-keyword">new</span> TransferServiceImpl();
  }

}</pre><p>The preceding configuration is exactly equivalent to the following
        Spring XML:
        </p><pre class="programlisting">&lt;<span class="hl-tag">beans</span>&gt;
  &lt;<span class="hl-tag">bean</span> <span class="hl-attribute">id</span>=<span class="hl-value">"transferService"</span> <span class="hl-attribute">class</span>=<span class="hl-value">"com.acme.TransferServiceImpl"</span>/&gt;
&lt;<span class="hl-tag">/beans</span>&gt;                </pre><p>Both declarations make a bean named <code class="code">transferService</code>
        available in the <code class="code">ApplicationContext</code>, bound to an object
        instance of type <code class="code">TransferServiceImpl</code>:
        </p><pre class="programlisting">
transferService -&gt; com.acme.TransferServiceImpl
              </pre></div><div class="section" lang="en"><div class="titlepage"><div><div><h4 class="title"><a name="beans-java-injecting-dependencies"></a>4.12.4.2&nbsp;Injecting dependencies</h4></div></div></div><p>When <code class="interfacename">@Bean</code>s have dependencies on one
        another, expressing that dependency is as simple as having one bean
        method call another:
        </p><pre class="programlisting">@Configuration
<span class="hl-keyword">public</span> <span class="hl-keyword">class</span> AppConfig {

  @Bean
  <span class="hl-keyword">public</span> Foo foo() {
      <span class="hl-keyword">return</span> <span class="hl-keyword">new</span> Foo(bar());
  }

  @Bean
  <span class="hl-keyword">public</span> Bar bar() {
      <span class="hl-keyword">return</span> <span class="hl-keyword">new</span> Bar();
  }

}                </pre><p>In the example above, the <code class="code">foo</code> bean receives a reference
        to <code class="code"> bar</code> via constructor injection.</p></div><div class="section" lang="en"><div class="titlepage"><div><div><h4 class="title"><a name="beans-java-lifecycle-callbacks"></a>4.12.4.3&nbsp;Receiving lifecycle callbacks</h4></div></div></div><p>Beans declared in a
        <code class="interfacename">@Configuration</code>-annotated class support
        the regular lifecycle callbacks. Any classes defined with the
        <code class="literal">@Bean</code> annotation can use the
        <code class="literal">@PostConstruct</code> and <code class="literal">@PreDestroy</code>
        annotations from JSR-250, see <a class="link" href="beans.html#beans-postconstruct-and-predestroy-annotations" title="4.9.6&nbsp;@PostConstruct and @PreDestroy">JSR-250
        annotations</a> for further details.</p><p>The regular Spring <a class="link" href="beans.html#beans-factory-nature" title="4.6&nbsp;Customizing the nature of a bean">lifecycle</a> callbacks are fully supported as well. If a bean
        implements <code class="code">InitializingBean</code>, <code class="code">DisposableBean</code>,
        or <code class="code">Lifecycle</code>, their respective methods are called by the
        container.</p><p>The standard set of <code class="code">*Aware</code> interfaces such as
        <code class="code"><a class="link" href="beans.html#beans-beanfactory" title="4.15&nbsp;The BeanFactory">BeanFactoryAware</a></code>,
        <code class="code"><a class="link" href="beans.html#beans-factory-aware" title="4.6.2&nbsp;ApplicationContextAware and BeanNameAware">BeanNameAware</a></code>,
        <code class="code"><a class="link" href="beans.html#context-functionality-messagesource" title="4.14.1&nbsp;Internationalization using MessageSource">MessageSourceAware</a></code>, <code class="code"><a class="link" href="beans.html#beans-factory-aware" title="4.6.2&nbsp;ApplicationContextAware and BeanNameAware">ApplicationContextAware</a></code>, and
        so on are also fully supported.</p><p>The <code class="interfacename">@Bean</code> annotation supports
        specifying arbitrary initialization and destruction callback methods,
        much like Spring XML's <code class="code">init-method</code> and
        <code class="code">destroy-method</code> attributes on the <code class="code">bean</code> element:
        </p><pre class="programlisting"><span class="hl-keyword">public</span> <span class="hl-keyword">class</span> Foo {
  <span class="hl-keyword">public</span> <span class="hl-keyword">void</span> init() {
      <span class="hl-comment">// initialization logic</span>
  }
}

<span class="hl-keyword">public</span> <span class="hl-keyword">class</span> Bar {
  <span class="hl-keyword">public</span> <span class="hl-keyword">void</span> cleanup() {
      <span class="hl-comment">// destruction logic</span>
  }
}

@Configuration
<span class="hl-keyword">public</span> <span class="hl-keyword">class</span> AppConfig {
  @Bean(initMethod = <span class="hl-string">"init"</span>)
  <span class="hl-keyword">public</span> Foo foo() {
      <span class="hl-keyword">return</span> <span class="hl-keyword">new</span> Foo();
  }
  @Bean(destroyMethod = <span class="hl-string">"cleanup"</span>)
  <span class="hl-keyword">public</span> Bar bar() {
      <span class="hl-keyword">return</span> <span class="hl-keyword">new</span> Bar();
  }
}
</pre><p>Of course, in the case of <code class="code">Foo</code> above, it would be
        equally as valid to call the <code class="code">init()</code> method directly during
        construction:
        </p><pre class="programlisting">@Configuration
<span class="hl-keyword">public</span> <span class="hl-keyword">class</span> AppConfig {
  @Bean
  <span class="hl-keyword">public</span> Foo foo() {
      Foo foo = <span class="hl-keyword">new</span> Foo();
      foo.init();
      <span class="hl-keyword">return</span> foo;
  }

  <span class="hl-comment">// ...</span>
}                    </pre><div class="tip" style="margin-left: 0.5in; margin-right: 0.5in;"><table border="0" summary="Tip"><tr><td rowspan="2" align="center" valign="top" width="25"><img alt="[Tip]" src="images/tip.gif"></td><th align="left">Tip</th></tr><tr><td align="left" valign="top"><p>When you work directly in Java, you can do anything you like with
          your objects and do not always need to rely on the container
          lifecycle!</p></td></tr></table></div></div><div class="section" lang="en"><div class="titlepage"><div><div><h4 class="title"><a name="beans-java-specifying-bean-scope"></a>4.12.4.4&nbsp;Specifying bean scope</h4></div></div></div><div class="section" lang="en"><div class="titlepage"><div><div><h5 class="title"><a name="beans-java-available-scopes"></a>Using the <code class="interfacename">@Scope</code>
          annotation</h5></div></div></div><p>You can specify that your beans defined with the
          <code class="interfacename">@Bean</code> annotation should have a specific
          scope. You can use any of the standard scopes specified in the <a class="link" href="beans.html#beans-factory-scopes" title="4.5&nbsp;Bean scopes">Bean Scopes</a> section.</p><p>The default scope is <code class="literal">singleton</code>, but you can
          override this with the <code class="interfacename">@Scope</code>
          annotation:
          </p><pre class="programlisting">@Configuration
<span class="hl-keyword">public</span> <span class="hl-keyword">class</span> MyConfiguration {
  @Bean
  @Scope(<span class="hl-string">"prototype"</span>)
  <span class="hl-keyword">public</span> Encryptor encryptor() {
      <span class="hl-comment">// ...</span>
  }
}</pre></div><div class="section" lang="en"><div class="titlepage"><div><div><h5 class="title"><a name="beans-java-scoped-proxy"></a><code class="code">@Scope and scoped-proxy</code></h5></div></div></div><p>Spring offers a convenient way of working with scoped dependencies
          through <a class="link" href="beans.html#beans-factory-scopes-other-injection" title="4.5.4.5&nbsp;Scoped beans as dependencies">scoped
          proxies</a>. The easiest way to create such a proxy when using the
          XML configuration is the <code class="code">&lt;aop:scoped-proxy/&gt;</code>
          element. Configuring your beans in Java with a @Scope annotation
          offers equivalent support with the proxyMode attribute. The default is
          no proxy (<code class="varname">ScopedProxyMode.NO</code>), but you can specify
          <code class="classname">ScopedProxyMode.TARGET_CLASS</code> or
          <code class="classname">ScopedProxyMode.INTERFACES</code>.</p><p>If you port the scoped proxy example from the XML reference
          documentation (see preceding link) to our
          <code class="interfacename">@Bean</code> using Java, it would look like
          the following:
          </p><pre class="programlisting"><span class="hl-comment">// an HTTP Session-scoped bean exposed as a proxy</span>
@Bean
@Scope(value = <span class="hl-string">"session"</span>, proxyMode = ScopedProxyMode.TARGET_CLASS)
<span class="hl-keyword">public</span> UserPreferences userPreferences() {
 <span class="hl-keyword">return</span> <span class="hl-keyword">new</span> UserPreferences();
}

@Bean
<span class="hl-keyword">public</span> Service userService() {
 UserService service = <span class="hl-keyword">new</span> SimpleUserService();
 <span class="hl-comment">// a reference to the proxied userPreferences bean</span>
 service.setUserPreferences(userPreferences());
 <span class="hl-keyword">return</span> service;
}                </pre></div><div class="section" lang="en"><div class="titlepage"><div><div><h5 class="title"><a name="beans-java-method-injection"></a>Lookup method injection</h5></div></div></div><p>As noted earlier, <a class="link" href="beans.html#beans-factory-method-injection" title="4.4.6&nbsp;Method injection">lookup method injection</a> is an advanced feature that you should
          use rarely. It is useful in cases where a singleton-scoped bean has a
          dependency on a prototype-scoped bean. Using Java for this type of
          configuration provides a natural means for implementing this pattern.
          </p><pre class="programlisting"><span class="hl-keyword">public</span> <span class="hl-keyword">abstract</span> <span class="hl-keyword">class</span> CommandManager {
  <span class="hl-keyword">public</span> Object process(Object commandState) {
      <span class="hl-comment">// grab a new instance of the appropriate Command interface</span>
      Command command = createCommand();

      <span class="hl-comment">// set the state on the (hopefully brand new) Command instance</span>
      command.setState(commandState);
      <span class="hl-keyword">return</span> command.execute();
  }

  <span class="hl-comment">// okay... but where is the implementation of this method?</span>
  <span class="hl-keyword">protected</span> <span class="hl-keyword">abstract</span> Command createCommand();
}                   </pre><p>Using Java-configuration support , you can create a subclass of
          <code class="code">CommandManager</code> where the abstract
          <code class="code">createCommand()</code> method is overridden in such a way that
          it looks up a new (prototype) command object:
          </p><pre class="programlisting">@Bean
@Scope(<span class="hl-string">"prototype"</span>)
<span class="hl-keyword">public</span> AsyncCommand asyncCommand() {
  AsyncCommand command = <span class="hl-keyword">new</span> AsyncCommand();
  <span class="hl-comment">// inject dependencies here as required</span>
  <span class="hl-keyword">return</span> command;
}

@Bean
<span class="hl-keyword">public</span> CommandManager commandManager() {
  <span class="hl-comment">// return new anonymous implementation of CommandManager with command() overridden</span>
  <span class="hl-comment">// to return a new prototype Command object</span>
  <span class="hl-keyword">return</span> <span class="hl-keyword">new</span> CommandManager() {
      <span class="hl-keyword">protected</span> Command createCommand() {
          <span class="hl-keyword">return</span> asyncCommand();
      }
  }
}                    </pre></div></div><div class="section" lang="en"><div class="titlepage"><div><div><h4 class="title"><a name="beans-java-customizing-bean-naming"></a>4.12.4.5&nbsp;Customizing bean naming</h4></div></div></div><p>By default, configuration classes use a
        <code class="interfacename">@Bean</code> method's name as the name of the
        resulting bean. This functionality can be overridden, however, with the
        <code class="code">name</code> attribute.
        </p><pre class="programlisting">@Configuration
<span class="hl-keyword">public</span> <span class="hl-keyword">class</span> AppConfig {

  @Bean(name = <span class="hl-string">"myFoo"</span>)
  <span class="hl-keyword">public</span> Foo foo() {
      <span class="hl-keyword">return</span> <span class="hl-keyword">new</span> Foo();
  }

}        </pre></div><div class="section" lang="en"><div class="titlepage"><div><div><h4 class="title"><a name="beans-java-bean-aliasing"></a>4.12.4.6&nbsp;Bean aliasing</h4></div></div></div><p>As discussed in <a class="xref" href="beans.html#beans-beanname" title="4.3.1&nbsp;Naming beans">Section&nbsp;4.3.1, &#8220;Naming beans&#8221;</a>, it is sometimes
        desirable to give a single bean multiple names, otherwise known as
        <span class="emphasis"><em>bean aliasing</em></span>. The <code class="literal">name</code>
        attribute of the <code class="literal">@Bean</code> annotation accepts a String
        array for this purpose.
        </p><pre class="programlisting">@Configuration
<span class="hl-keyword">public</span> <span class="hl-keyword">class</span> AppConfig {

  @Bean(name = { <span class="hl-string">"dataSource"</span>, <span class="hl-string">"subsystemA-dataSource"</span>, <span class="hl-string">"subsystemB-dataSource"</span> })
  <span class="hl-keyword">public</span> DataSource dataSource() {
      <span class="hl-comment">// instantiate, configure and return DataSource bean...</span>
  }

}        </pre></div></div><div class="section" lang="en"><div class="titlepage"><div><div><h3 class="title"><a name="beans-java-further-information-java-config"></a>4.12.5&nbsp;Further information about how Java-based configuration works
      internally</h3></div></div></div><p>The following example shows a <code class="literal">@Bean</code> annotated
      method being called twice:</p><pre class="programlisting">
@Configuration
<span class="hl-keyword">public</span> <span class="hl-keyword">class</span> AppConfig {

  @Bean
  <span class="hl-keyword">public</span> ClientService clientService1() {
    ClientServiceImpl clientService = <span class="hl-keyword">new</span> ClientServiceImpl();
    clientService.setClientDao(clientDao());
    <span class="hl-keyword">return</span> clientService;
  }
  @Bean
  <span class="hl-keyword">public</span> ClientService clientService2() {
    ClientServiceImpl clientService = <span class="hl-keyword">new</span> ClientServiceImpl();
    clientService.setClientDao(clientDao());
    <span class="hl-keyword">return</span> clientService;
  }

  @Bean
  <span class="hl-keyword">public</span> ClientDao clientDao() {
    <span class="hl-keyword">return</span> <span class="hl-keyword">new</span> ClientDaoImpl();
  }
}
    </pre><p> <code class="methodname">clientDao()</code> has been called once in
      <code class="methodname">clientService1()</code> and once in
      <code class="methodname">clientService2()</code>. Since this method creates a new
      instance of <code class="classname">ClientDaoImpl</code> and returns it, you would
      normally expect having 2 instances (one for each service). That definitely
      would be problematic: in Spring, instantiated beans have a
      <code class="literal">singleton</code> scope by default. This is where the magic
      comes in: All <code class="literal">@Configuration</code> classes are subclassed at
      startup-time with <code class="literal">CGLIB</code>. In the subclass, the child
      method checks the container first for any cached (scoped) beans before it
      calls the parent method and creates a new instance. </p><div class="note" style="margin-left: 0.5in; margin-right: 0.5in;"><table border="0" summary="Note"><tr><td rowspan="2" align="center" valign="top" width="25"><img alt="[Note]" src="images/note.gif"></td><th align="left">Note</th></tr><tr><td align="left" valign="top"><p> The behavior could be different according to the scope of your
        bean. We are talking about singletons here. </p></td></tr></table></div><div class="note" style="margin-left: 0.5in; margin-right: 0.5in;"><table border="0" summary="Note"><tr><td rowspan="2" align="center" valign="top" width="25"><img alt="[Note]" src="images/note.gif"></td><th align="left">Note</th></tr><tr><td align="left" valign="top"><p> Beware that, in order for JavaConfig to work, you must include the
        CGLIB jar in your list of dependencies. </p></td></tr></table></div><div class="note" style="margin-left: 0.5in; margin-right: 0.5in;"><table border="0" summary="Note"><tr><td rowspan="2" align="center" valign="top" width="25"><img alt="[Note]" src="images/note.gif"></td><th align="left">Note</th></tr><tr><td align="left" valign="top"><p> There are a few restrictions due to the fact that CGLIB dynamically
        adds features at startup-time: </p><div class="itemizedlist"><ul type="disc"><li><p>Configuration classes should not be final</p></li><li><p>They should have a constructor with no arguments</p></li></ul></div><p> </p></td></tr></table></div></div></div><div class="section" lang="en"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="context-load-time-weaver"></a>4.13&nbsp;Registering a <code class="interfacename">LoadTimeWeaver</code></h2></div></div></div><p>The <code class="literal">context</code> namespace introduced in Spring 2.5
      provides a <code class="literal">load-time-weaver</code>
      element.</p><pre class="programlisting">&lt;<span class="hl-tag">beans</span>&gt;

     &lt;<span class="hl-tag">context:load-time-weaver</span>/&gt;

&lt;<span class="hl-tag">/beans</span>&gt;</pre><p>Adding this element to an XML-based Spring configuration file
      activates a Spring <code class="interfacename">LoadTimeWeaver</code> for the
      <code class="interfacename">ApplicationContext</code>. Any bean within that
      <code class="interfacename">ApplicationContext</code> may implement
      <code class="interfacename">LoadTimeWeaverAware</code>, thereby receiving a
      reference to the load-time weaver instance. This is particularly useful in
      combination with <a class="link" href="orm.html#orm-jpa" title="14.5&nbsp;JPA">Spring's JPA support</a> where
      load-time weaving may be necessary for JPA class transformation. Consult
      the <code class="classname">LocalContainerEntityManagerFactoryBean</code> Javadoc
      for more detail. For more on AspectJ load-time weaving, see <a class="xref" href="aop.html#aop-aj-ltw" title="8.8.4&nbsp;Load-time weaving with AspectJ in the Spring Framework">Section&nbsp;8.8.4, &#8220;Load-time weaving with AspectJ in the Spring Framework&#8221;</a>.</p></div><div class="section" lang="en"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="context-introduction"></a>4.14&nbsp;Additional Capabilities of the
    <code class="interfacename">ApplicationContext</code></h2></div></div></div><p>As was discussed in the chapter introduction, the
    <code class="literal">org.springframework.beans.factory</code> package provides basic
    functionality for managing and manipulating beans, including in a
    programmatic way. The <code class="literal">org.springframework.context</code> package
    adds the <a class="ulink" href="http://static.springframework.org/spring/docs/3.0.x/javadoc-api/org/springframework/context/ApplicationContext.html" target="_top"><code class="interfacename">ApplicationContext</code></a> interface, which
    extends the <code class="interfacename">BeanFactory</code> interface, in
    addition to extending other interfaces to provide additional functionality
    in a more <span class="emphasis"><em>application framework-oriented style</em></span>. Many
    people use the <code class="interfacename">ApplicationContext</code> in a
    completely declarative fashion, not even creating it programmatically, but
    instead relying on support classes such as
    <code class="classname">ContextLoader</code> to automatically instantiate an
    <code class="interfacename">ApplicationContext</code> as part of the normal
    startup process of a J2EE web application.</p><p>To enhance <code class="interfacename">BeanFactory</code> functionality in a
    more framework-oriented style the context package also provides the
    following functionality:</p><div class="itemizedlist"><ul type="disc"><li><p><span class="emphasis"><em>Access to messages in i18n-style</em></span>, through the
        <code class="interfacename">MessageSource</code> interface.</p></li><li><p><span class="emphasis"><em>Access to resources</em></span>, such as URLs and files,
        through the <code class="interfacename">ResourceLoader</code>
        interface.</p></li><li><p><span class="emphasis"><em>Event publication</em></span> to beans implementing the
        <code class="interfacename">ApplicationListener</code> interface, through
        the use of the <code class="interfacename">ApplicationEventPublisher</code>
        interface.</p></li><li><p><span class="emphasis"><em>Loading of multiple (hierarchical) contexts</em></span>,
        allowing each to be focused on one particular layer, such as the web
        layer of an application, through the
        <code class="interfacename">HierarchicalBeanFactory</code> interface.</p></li></ul></div><div class="section" lang="en"><div class="titlepage"><div><div><h3 class="title"><a name="context-functionality-messagesource"></a>4.14.1&nbsp;Internationalization using
      <code class="interfacename">MessageSource</code></h3></div></div></div><p>The <code class="interfacename">ApplicationContext</code> interface
      extends an interface called <code class="interfacename">MessageSource</code>,
      and therefore provides internationalization (i18n) functionality. Spring
      also provides the interface
      <code class="classname">HierarchicalMessageSource</code>, which can resolve
      messages hierarchically. Together these interfaces provide the foundation
      upon which Spring effects message resolution. The methods defined on these
      interfaces include:</p><div class="itemizedlist"><ul type="disc"><li><p><code class="methodname">String getMessage(String code, Object[] args, String
          default, Locale loc)</code>: The basic method used to retrieve a
          message from the <code class="interfacename">MessageSource</code>. When no
          message is found for the specified locale, the default message is
          used. Any arguments passed in become replacement values, using the
          <code class="interfacename">MessageFormat</code> functionality provided by
          the standard library.</p></li><li><p><code class="methodname">String getMessage(String code, Object[] args, Locale
          loc)</code>: Essentially the same as the previous method, but
          with one difference: no default message can be specified; if the
          message cannot be found, a
          <code class="classname">NoSuchMessageException</code> is thrown.</p></li><li><p><code class="methodname">String getMessage(MessageSourceResolvable resolvable,
          Locale locale)</code>: All properties used in the preceding
          methods are also wrapped in a class named
          <code class="interfacename">MessageSourceResolvable</code>, which you can
          use with this method.</p></li></ul></div><p>When an <code class="interfacename">ApplicationContext</code> is loaded,
      it automatically searches for a
      <code class="interfacename">MessageSource</code> bean defined in the context.
      The bean must have the name <code class="literal">messageSource</code>. If such a
      bean is found, all calls to the preceding methods are delegated to the
      message source. If no message source is found, the
      <code class="interfacename">ApplicationContext</code> attempts to find a
      parent containing a bean with the same name. If it does, it uses that bean
      as the <code class="interfacename">MessageSource</code>. If the
      <code class="interfacename">ApplicationContext</code> cannot find any source
      for messages, an empty <code class="classname">DelegatingMessageSource</code> is
      instantiated in order to be able to accept calls to the methods defined
      above.</p><p>Spring provides two <code class="interfacename">MessageSource</code>
      implementations, <code class="classname">ResourceBundleMessageSource</code> and
      <code class="classname">StaticMessageSource</code>. Both implement
      <code class="interfacename">HierarchicalMessageSource</code> in order to do
      nested messaging. The <code class="classname">StaticMessageSource</code> is rarely
      used but provides programmatic ways to add messages to the source. The
      <code class="classname">ResourceBundleMessageSource</code> is shown in the
      following example:</p><pre class="programlisting">&lt;<span class="hl-tag">beans</span>&gt;
&lt;<span class="hl-tag">bean</span> <span class="hl-attribute">id</span>=<span class="hl-value">"messageSource"</span>
      <span class="hl-attribute">class</span>=<span class="hl-value">"org.springframework.context.support.ResourceBundleMessageSource"</span>&gt;
  &lt;<span class="hl-tag">property</span> <span class="hl-attribute">name</span>=<span class="hl-value">"basenames"</span>&gt;
    &lt;<span class="hl-tag">list</span>&gt;
      &lt;<span class="hl-tag">value</span>&gt;format&lt;<span class="hl-tag">/value</span>&gt;
      &lt;<span class="hl-tag">value</span>&gt;exceptions&lt;<span class="hl-tag">/value</span>&gt;
      &lt;<span class="hl-tag">value</span>&gt;windows&lt;<span class="hl-tag">/value</span>&gt;
    &lt;<span class="hl-tag">/list</span>&gt;
  &lt;<span class="hl-tag">/property</span>&gt;
&lt;<span class="hl-tag">/bean</span>&gt;
&lt;<span class="hl-tag">/beans</span>&gt;</pre><p>In the example it is assumed you have three resource bundles defined
      in your classpath called <code class="literal">format</code>,
      <code class="literal">exceptions</code> and <code class="literal">windows</code>. Any request
      to resolve a message will be handled in the JDK standard way of resolving
      messages through ResourceBundles. For the purposes of the example, assume
      the contents of two of the above resource bundle files are...</p><pre class="programlisting"># in format.properties
message=Alligators rock!</pre><pre class="programlisting"># in exceptions.properties
argument.required=The <span class="hl-string">'{0}'</span> argument is required.</pre><p>A program to execute the <code class="classname">MessageSource</code>
      functionality is shown in the next example. Remember that all
      <code class="classname">ApplicationContext</code> implementations are also
      <code class="classname">MessageSource</code> implementations and so can be cast to
      the <code class="classname">MessageSource</code> interface.</p><pre class="programlisting"><span class="hl-keyword">public</span> <span class="hl-keyword">static</span> <span class="hl-keyword">void</span> main(String[] args) {
  MessageSource resources = <span class="hl-keyword">new</span> ClassPathXmlApplicationContext(<span class="hl-string">"beans.xml"</span>);
  String message = resources.getMessage(<span class="hl-string">"message"</span>, null, <span class="hl-string">"Default"</span>, null);
  System.out.println(message);
}</pre><p>The resulting output from the above program will be...</p><pre class="programlisting">Alligators rock!</pre><p>So to summarize, the <code class="classname">MessageSource</code> is defined
      in a file called <code class="literal">beans.xml</code>, which exists at the root of
      your classpath. The <code class="literal">messageSource</code> bean definition
      refers to a number of resource bundles through its
      <code class="literal">basenames</code> property. The three files that are passed in
      the list to the <code class="literal">basenames</code> property exist as files at
      the root of your classpath and are called
      <code class="literal">format.properties</code>,
      <code class="literal">exceptions.properties</code>, and
      <code class="literal">windows.properties</code> respectively.</p><p>The next example shows arguments passed to the message lookup; these
      arguments will be converted into Strings and inserted into placeholders in
      the lookup message.</p><pre class="programlisting">&lt;<span class="hl-tag">beans</span>&gt;

  &lt;<span class="hl-comment">!-- this MessageSource is being used in a web application --</span>&gt;
  &lt;<span class="hl-tag">bean</span> <span class="hl-attribute">id</span>=<span class="hl-value">"messageSource"</span> <span class="hl-attribute">class</span>=<span class="hl-value">"org.springframework.context.support.ResourceBundleMessageSource"</span>&gt;
      &lt;<span class="hl-tag">property</span> <span class="hl-attribute">name</span>=<span class="hl-value">"basename"</span> <span class="hl-attribute">value</span>=<span class="hl-value">"test-messages"</span>/&gt;
  &lt;<span class="hl-tag">/bean</span>&gt;

  &lt;<span class="hl-comment">!-- lets inject the above MessageSource into this POJO --</span>&gt;
  &lt;<span class="hl-tag">bean</span> <span class="hl-attribute">id</span>=<span class="hl-value">"example"</span> <span class="hl-attribute">class</span>=<span class="hl-value">"com.foo.Example"</span>&gt;
      &lt;<span class="hl-tag">property</span> <span class="hl-attribute">name</span>=<span class="hl-value">"messages"</span> <span class="hl-attribute">ref</span>=<span class="hl-value">"messageSource"</span>/&gt;
  &lt;<span class="hl-tag">/bean</span>&gt;

&lt;<span class="hl-tag">/beans</span>&gt;</pre><pre class="programlisting"><span class="hl-keyword">public</span> <span class="hl-keyword">class</span> Example {

  <span class="hl-keyword">private</span> MessageSource messages;

  <span class="hl-keyword">public</span> <span class="hl-keyword">void</span> setMessages(MessageSource messages) {
      <span class="hl-keyword">this</span>.messages = messages;
  }

  <span class="hl-keyword">public</span> <span class="hl-keyword">void</span> execute() {
      String message = <span class="hl-keyword">this</span>.messages.getMessage(<span class="hl-string">"argument.required"</span>,
          <span class="hl-keyword">new</span> Object [] {<span class="hl-string">"userDao"</span>}, <span class="hl-string">"Required"</span>, null);
      System.out.println(message);
  }

}</pre><p>The resulting output from the invocation of the
      <code class="methodname">execute()</code> method will be...</p><pre class="programlisting">The userDao argument is required.</pre><p>With regard to internationalization (i18n), Spring's various
      <code class="classname">MessageResource</code> implementations follow the same
      locale resolution and fallback rules as the standard JDK
      <code class="classname">ResourceBundle</code>. In short, and continuing with the
      example <code class="literal">messageSource</code> defined previously, if you want
      to resolve messages against the British (en-GB) locale, you would create
      files called <code class="literal">format_en_GB.properties</code>,
      <code class="literal">exceptions_en_GB.properties</code>, and
      <code class="literal">windows_en_GB.properties</code> respectively.</p><p>Typically, locale resolution is managed by the surrounding environment
      of the application. In this example, the locale against which (British)
      messages will be resolved is specified manually.</p><pre class="programlisting"><em class="lineannotation"><span class="lineannotation"># in exceptions_en_GB.properties</span></em>
argument.required=Ebagum lad, the '{0}' argument is required, I say, required.</pre><pre class="programlisting"><span class="hl-keyword">public</span> <span class="hl-keyword">static</span> <span class="hl-keyword">void</span> main(<span class="hl-keyword">final</span> String[] args) {
  MessageSource resources = <span class="hl-keyword">new</span> ClassPathXmlApplicationContext(<span class="hl-string">"beans.xml"</span>);
  String message = resources.getMessage(<span class="hl-string">"argument.required"</span>,
      <span class="hl-keyword">new</span> Object [] {<span class="hl-string">"userDao"</span>}, <span class="hl-string">"Required"</span>, Locale.UK);
  System.out.println(message);
}</pre><p>The resulting output from the running of the above program will
      be...</p><pre class="programlisting">Ebagum lad, the 'userDao' argument is required, I say, required.</pre><p>You can also use the <code class="classname">MessageSourceAware</code>
      interface to acquire a reference to any
      <code class="classname">MessageSource</code> that has been defined. Any bean that
      is defined in an <code class="classname">ApplicationContext</code> that implements
      the <code class="classname">MessageSourceAware</code> interface is injected with
      the application context's <code class="classname">MessageSource</code> when the
      bean is created and configured.</p><div class="note" style="margin-left: 0.5in; margin-right: 0.5in;"><table border="0" summary="Note"><tr><td rowspan="2" align="center" valign="top" width="25"><img alt="[Note]" src="images/note.gif"></td><th align="left">Note</th></tr><tr><td align="left" valign="top"><p><span class="emphasis"><em>As an alternative to
        <code class="classname">ResourceBundleMessageSource</code>, Spring provides a
        <code class="classname">ReloadableResourceBundleMessageSource</code> class. This
        variant supports the same bundle file format but is more flexible than
        the standard JDK based
        <code class="classname">ResourceBundleMessageSource</code>
        implementation.</em></span> In particular, it allows for reading files
        from any Spring resource location (not just from the classpath) and
        supports hot reloading of bundle property files (while efficiently
        caching them in between). Check out the
        <code class="classname">ReloadableResourceBundleMessageSource</code> javadoc for
        details.</p></td></tr></table></div></div><div class="section" lang="en"><div class="titlepage"><div><div><h3 class="title"><a name="context-functionality-events"></a>4.14.2&nbsp;Standard and Custom Events</h3></div></div></div><p>Event handling in the
      <code class="interfacename">ApplicationContext</code> is provided through the
      <code class="classname">ApplicationEvent</code> class and
      <code class="interfacename">ApplicationListener</code> interface. If a bean
      that implements the <code class="interfacename">ApplicationListener</code>
      interface is deployed into the context, every time an
      <code class="classname">ApplicationEvent</code> gets published to the
      <code class="interfacename">ApplicationContext</code>, that bean is notified.
      Essentially, this is the standard <span class="emphasis"><em>Observer</em></span> design
      pattern. Spring provides the following standard events:</p><div class="table"><a name="beans-ctx-events-tbl"></a><p class="title"><b>Table&nbsp;4.7.&nbsp;Built-in Events</b></p><div class="table-contents"><table summary="Built-in Events" style="border-collapse: collapse;border-top: 1.0pt solid ; border-bottom: 1.0pt solid ; border-left: 1.0pt solid ; border-right: 1.0pt solid ; "><colgroup><col><col></colgroup><thead><tr><th style="border-right: 1.0pt solid ; border-bottom: 1.0pt solid ; ">Event</th><th style="border-bottom: 1.0pt solid ; ">Explanation</th></tr></thead><tbody><tr><td style="border-right: 1.0pt solid ; border-bottom: 1.0pt solid ; "><code class="classname">ContextRefreshedEvent</code></td><td style="border-bottom: 1.0pt solid ; ">Published when the
              <code class="interfacename">ApplicationContext</code> is initialized
              or refreshed, for example, using the
              <code class="methodname">refresh()</code> method on the
              <code class="interfacename">ConfigurableApplicationContext</code>
              interface. "Initialized" here means that all beans are loaded,
              post-processor beans are detected and activated, singletons are
              pre-instantiated, and the
              <code class="interfacename">ApplicationContext</code> object is ready
              for use. As long as the context has not been closed, a refresh can
              be triggered multiple times, provided that the chosen
              <code class="interfacename">ApplicationContext</code> actually
              supports such "hot" refreshes. For example,
              <code class="classname">XmlWebApplicationContext</code> supports hot
              refreshes, but <code class="classname">GenericApplicationContext</code>
              does not.</td></tr><tr><td style="border-right: 1.0pt solid ; border-bottom: 1.0pt solid ; "><code class="classname">ContextStartedEvent</code></td><td style="border-bottom: 1.0pt solid ; ">Published when the
              <code class="interfacename">ApplicationContext</code> is started,
              using the <code class="methodname">start()</code> method on the
              <code class="interfacename">ConfigurableApplicationContext</code>
              interface. "Started" here means that all
              <code class="interfacename">Lifecycle</code> beans receive an explicit
              start signal. Typically this signal is used to restart beans after
              an explicit stop, but it may also be used to start components that
              have not been configured for autostart , for example, components
              that have not already started on initialization.</td></tr><tr><td style="border-right: 1.0pt solid ; border-bottom: 1.0pt solid ; "><code class="classname">ContextStoppedEvent</code></td><td style="border-bottom: 1.0pt solid ; ">Published when the
              <code class="interfacename">ApplicationContext</code> is stopped,
              using the <code class="methodname">stop()</code> method on the
              <code class="interfacename">ConfigurableApplicationContext</code>
              interface. "Stopped" here means that all
              <code class="interfacename">Lifecycle</code> beans receive an explicit
              stop signal. A stopped context may be restarted through a
              <code class="methodname">start()</code> call.</td></tr><tr><td style="border-right: 1.0pt solid ; border-bottom: 1.0pt solid ; "><code class="classname">ContextClosedEvent</code></td><td style="border-bottom: 1.0pt solid ; ">Published when the
              <code class="interfacename">ApplicationContext</code> is closed, using
              the <code class="methodname">close()</code> method on the
              <code class="interfacename">ConfigurableApplicationContext</code>
              interface. "Closed" here means that all singleton beans are
              destroyed. A closed context reaches its end of life; it cannot be
              refreshed or restarted.</td></tr><tr><td style="border-right: 1.0pt solid ; "><code class="classname">RequestHandledEvent</code></td><td style="">A web-specific event telling all beans that an HTTP request
              has been serviced. This event is published
              <span class="emphasis"><em>after</em></span> the request is complete. This event is
              only applicable to web applications using Spring's
              <code class="classname">DispatcherServlet</code>.</td></tr></tbody></table></div></div><br class="table-break"><p>You can also create and publish your own custom events. This example
      demonstrates a simple class that extends Spring's
      <code class="classname">ApplicationEvent</code> base class:</p><pre class="programlisting"><span class="hl-keyword">public</span> <span class="hl-keyword">class</span> BlackListEvent <span class="hl-keyword">extends</span> ApplicationEvent {
  <span class="hl-keyword">private</span> <span class="hl-keyword">final</span> String address;
  <span class="hl-keyword">private</span> <span class="hl-keyword">final</span> String test;

  <span class="hl-keyword">public</span> BlackListEvent(Object source, String address, String test) {
      <span class="hl-keyword">super</span>(source);
      <span class="hl-keyword">this</span>.address = address;
      <span class="hl-keyword">this</span>.test = test;
  }

  <span class="hl-comment">// accessor and other methods...</span>
}</pre><p>To publish a custom <code class="classname">ApplicationEvent</code>, call the
      <code class="methodname">publishEvent()</code> method on an
      <code class="interfacename">ApplicationEventPublisher</code>. Typically this
      is done by creating a class that implements
      <code class="interfacename">ApplicationEventPublisherAware</code> and
      registering it as a Spring bean. The following example demonstrates such a
      class:</p><pre class="programlisting"><span class="hl-keyword">public</span> <span class="hl-keyword">class</span> EmailService <span class="hl-keyword">implements</span> ApplicationEventPublisherAware {

  <span class="hl-keyword">private</span> List&lt;String&gt; blackList;
  <span class="hl-keyword">private</span> ApplicationEventPublisher publisher;

  <span class="hl-keyword">public</span> <span class="hl-keyword">void</span> setBlackList(List&lt;String&gt; blackList) {
      <span class="hl-keyword">this</span>.blackList = blackList;
  }

  <span class="hl-keyword">public</span> <span class="hl-keyword">void</span> setApplicationEventPublisher(ApplicationEventPublisher publisher) {
      <span class="hl-keyword">this</span>.publisher = publisher;
  }

  <span class="hl-keyword">public</span> <span class="hl-keyword">void</span> sendEmail(String address, String text) {
      <span class="hl-keyword">if</span> (blackList.contains(address)) {
          BlackListEvent event = <span class="hl-keyword">new</span> BlackListEvent(<span class="hl-keyword">this</span>, address, text);
          publisher.publishEvent(event);
          <span class="hl-keyword">return</span>;
      }
      <span class="hl-comment">// send email...</span>
  }
}</pre><p>At configuration time, the Spring container will detect that
      <code class="classname">EmailService</code> implements
      <code class="interfacename">ApplicationEventPublisherAware</code> and will
      automatically call
      <code class="methodname">setApplicationEventPublisher()</code>. In reality, the
      parameter passed in will be the Spring container itself; you're simply
      interacting with the application context via its
      <code class="interfacename">ApplicationEventPublisher</code> interface.</p><p>To receive the custom <code class="classname">ApplicationEvent</code>, create
      a class that implements <code class="interfacename">ApplicationListener</code>
      and register it as a Spring bean. The following example demonstrates such
      a class:</p><pre class="programlisting"><span class="hl-keyword">public</span> <span class="hl-keyword">class</span> BlackListNotifier <span class="hl-keyword">implements</span> ApplicationListener&lt;BlackListEvent&gt; {

  <span class="hl-keyword">private</span> String notificationAddress;

  <span class="hl-keyword">public</span> <span class="hl-keyword">void</span> setNotificationAddress(String notificationAddress) {
      <span class="hl-keyword">this</span>.notificationAddress = notificationAddress;
  }

  <span class="hl-keyword">public</span> <span class="hl-keyword">void</span> onApplicationEvent(BlackListEvent event) {
        <span class="hl-comment">// notify appropriate parties via notificationAddress...</span>
  }
}</pre><p>Notice that <code class="interfacename">ApplicationListener</code> is
      generically parameterized with the type of your custom event,
      <code class="classname">BlackListEvent</code>. This means that the
      <code class="methodname">onApplicationEvent()</code> method can remain type-safe,
      avoiding any need for downcasting. You may register as many event
      listeners as you wish, but note that by default event listeners receive
      events synchronously. This means the
      <code class="methodname">publishEvent()</code> method blocks until all listeners
      have finished processing the event. One advantage of this synchronous and
      single-threaded approach is that when a listener receives an event, it
      operates inside the transaction context of the publisher if a transaction
      context is available. If another strategy for event publication becomes
      necessary, refer to the JavaDoc for Spring's
      <code class="interfacename">ApplicationEventMulticaster</code>
      interface.</p><p>The following example demonstrates the bean definitions used to
      register and configure each of the classes above:</p><pre class="programlisting">&lt;<span class="hl-tag">bean</span> <span class="hl-attribute">id</span>=<span class="hl-value">"emailService"</span> <span class="hl-attribute">class</span>=<span class="hl-value">"example.EmailService"</span>&gt;
  &lt;<span class="hl-tag">property</span> <span class="hl-attribute">name</span>=<span class="hl-value">"blackList"</span>&gt;
      &lt;<span class="hl-tag">list</span>&gt;
          &lt;<span class="hl-tag">value</span>&gt;black@list.org&lt;<span class="hl-tag">/value</span>&gt;
          &lt;<span class="hl-tag">value</span>&gt;white@list.org&lt;<span class="hl-tag">/value</span>&gt;
          &lt;<span class="hl-tag">value</span>&gt;john@doe.org&lt;<span class="hl-tag">/value</span>&gt;
      &lt;<span class="hl-tag">/list</span>&gt;
  &lt;<span class="hl-tag">/property</span>&gt;
&lt;<span class="hl-tag">/bean</span>&gt;

&lt;<span class="hl-tag">bean</span> <span class="hl-attribute">id</span>=<span class="hl-value">"blackListNotifier"</span> <span class="hl-attribute">class</span>=<span class="hl-value">"example.BlackListNotifier"</span>&gt;
  &lt;<span class="hl-tag">property</span> <span class="hl-attribute">name</span>=<span class="hl-value">"notificationAddress"</span> <span class="hl-attribute">value</span>=<span class="hl-value">"spam@list.org"</span>/&gt;
&lt;<span class="hl-tag">/bean</span>&gt;</pre><p>Putting it all together, when the <code class="methodname">sendEmail()</code>
      method of the <code class="literal">emailService</code> bean is called, if there are
      any emails that should be blacklisted, a custom event of type
      <code class="classname">BlackListEvent</code> is published. The
      <code class="literal">blackListNotifier</code> bean is registered as an
      <code class="interfacename">ApplicationListener</code> and thus receives the
      <code class="classname">BlackListEvent</code>, at which point it can notify
      appropriate parties.</p><div class="note" style="margin-left: 0.5in; margin-right: 0.5in;"><table border="0" summary="Note"><tr><td rowspan="2" align="center" valign="top" width="25"><img alt="[Note]" src="images/note.gif"></td><th align="left">Note</th></tr><tr><td align="left" valign="top"><p>Spring's eventing mechanism is designed for simple communication
        between Spring beans within the same application context. However, for
        more sophisticated enterprise integration needs, the
        separately-maintained <a class="ulink" href="http://springsource.org/spring-integration" target="_top">Spring
        Integration</a> project provides complete support for building
        lightweight, <a class="ulink" href="http://www.enterpriseintegrationpatterns.com" target="_top">pattern-oriented</a>, event-driven architectures that build upon
        the well-known Spring programming model.</p></td></tr></table></div></div><div class="section" lang="en"><div class="titlepage"><div><div><h3 class="title"><a name="context-functionality-resources"></a>4.14.3&nbsp;Convenient access to low-level resources</h3></div></div></div><p>For optimal usage and understanding of application contexts, users
      should generally familiarize themselves with Spring's
      <code class="interfacename">Resource</code> abstraction, as described in the
      chapter <a class="xref" href="resources.html" title="5.&nbsp;Resources">Chapter&nbsp;5, <i>Resources</i></a>.</p><p>An application context is a
      <code class="interfacename">ResourceLoader</code>, which can be used to load
      <code class="interfacename">Resource</code>s. A
      <code class="interfacename">Resource</code> is essentially a more feature rich
      version of the JDK class <code class="literal">java.net.URL</code>, in fact, the
      implementations of the <code class="interfacename">Resource</code> wrap an
      instance of <code class="literal">java.net.URL</code> where appropriate. A
      <code class="interfacename">Resource</code> can obtain low-level resources
      from almost any location in a transparent fashion, including from the
      classpath, a filesystem location, anywhere describable with a standard
      URL, and some other variations. If the resource location string is a
      simple path without any special prefixes, where those resources come from
      is specific and appropriate to the actual application context type.</p><p>You can configure a bean deployed into the application context to
      implement the special callback interface,
      <code class="interfacename">ResourceLoaderAware</code>, to be automatically
      called back at initialization time with the application context itself
      passed in as the <code class="interfacename">ResourceLoader</code>. You can
      also expose properties of type <code class="interfacename">Resource</code>, to
      be used to access static resources; they will be injected into it like any
      other properties. You can specify those
      <code class="interfacename">Resource</code> properties as simple String paths,
      and rely on a special JavaBean
      <code class="interfacename">PropertyEditor</code> that is automatically
      registered by the context, to convert those text strings to actual
      <code class="interfacename">Resource</code> objects when the bean is
      deployed.</p><p>The location path or paths supplied to an
      <code class="interfacename">ApplicationContext</code> constructor are actually
      resource strings, and in simple form are treated appropriately to the
      specific context implementation.
      <code class="classname">ClassPathXmlApplicationContext</code> treats a simple
      location path as a classpath location. You can also use location paths
      (resource strings) with special prefixes to force loading of definitions
      from the classpath or a URL, regardless of the actual context type.</p></div><div class="section" lang="en"><div class="titlepage"><div><div><h3 class="title"><a name="context-create"></a>4.14.4&nbsp;Convenient <code class="interfacename">ApplicationContext</code>
      instantiation for web applications</h3></div></div></div><p>You can create <code class="interfacename">ApplicationContext</code>
      instances declaratively by using, for example, a
      <code class="classname">ContextLoader</code>. Of course you can also create
      <code class="interfacename">ApplicationContext</code> instances
      programmatically by using one of the
      <code class="interfacename">ApplicationContext</code> implementations.</p><p>The <code class="classname">ContextLoader</code> mechanism comes in two
      flavors: the <code class="classname">ContextLoaderListener</code> and the
      <code class="classname">ContextLoaderServlet</code>. They have the same
      functionality but differ in that the listener version is not reliable in
      Servlet 2.3 containers. In the Servlet 2.4 specification, Servlet context
      listeners must execute immediately after the Servlet context for the web
      application is created and is available to service the first request (and
      also when the Servlet context is about to be shut down). As such a Servlet
      context listener is an ideal place to initialize the Spring
      <code class="interfacename">ApplicationContext</code>. All things being equal,
      you should probably prefer <code class="classname">ContextLoaderListener</code>;
      for more information on compatibility, have a look at the Javadoc for the
      <code class="classname">ContextLoaderServlet</code>.</p><p>You can register an <code class="interfacename">ApplicationContext</code>
      using the <code class="classname">ContextLoaderListener</code> as follows:</p><pre class="programlisting">&lt;<span class="hl-tag">context-param</span>&gt;
&lt;<span class="hl-tag">param-name</span>&gt;contextConfigLocation&lt;<span class="hl-tag">/param-name</span>&gt;
&lt;<span class="hl-tag">param-value</span>&gt;/WEB-INF/daoContext.xml /WEB-INF/applicationContext.xml&lt;<span class="hl-tag">/param-value</span>&gt;
&lt;<span class="hl-tag">/context-param</span>&gt;

&lt;<span class="hl-tag">listener</span>&gt;
&lt;<span class="hl-tag">listener-class</span>&gt;org.springframework.web.context.ContextLoaderListener&lt;<span class="hl-tag">/listener-class</span>&gt;
&lt;<span class="hl-tag">/listener</span>&gt;

&lt;<span class="hl-comment">!-- or use the ContextLoaderServlet instead of the above listener
&lt;servlet&gt;
&lt;servlet-name&gt;context&lt;/servlet-name&gt;
&lt;servlet-class&gt;org.springframework.web.context.ContextLoaderServlet&lt;/servlet-class&gt;
&lt;load-on-startup&gt;1&lt;/load-on-startup&gt;
&lt;/servlet&gt;
--</span>&gt;</pre><p>The listener inspects the <code class="literal">contextConfigLocation</code>
      parameter. If the parameter does not exist, the listener uses
      <code class="literal">/WEB-INF/applicationContext.xml</code> as a default. When the
      parameter <span class="emphasis"><em>does</em></span> exist, the listener separates the
      String by using predefined delimiters (comma, semicolon and whitespace)
      and uses the values as locations where application contexts will be
      searched. Ant-style path patterns are supported as well. Examples are
      <code class="literal">/WEB-INF/*Context.xml</code> for all files with names ending
      with "Context.xml", residing in the "WEB-INF" directory, and
      <code class="literal">/WEB-INF/**/*Context.xml</code>, for all such files in any
      subdirectory of "WEB-INF".</p><p>You can use <code class="classname">ContextLoaderServlet</code> instead of
      <code class="classname">ContextLoaderListener</code>. The Servlet uses the
      <code class="literal">contextConfigLocation</code> parameter just as the listener
      does.</p></div><div class="section" lang="en"><div class="titlepage"><div><div><h3 class="title"><a name="d0e9393"></a>4.14.5&nbsp;Deploying a Spring ApplicationContext as a J2EE RAR file</h3></div></div></div><p>In Spring 2.5 and later, it is possible to deploy a Spring
      ApplicationContext as a RAR file, encapsulating the context and all of its
      required bean classes and library JARs in a J2EE RAR deployment unit. This
      is the equivalent of bootstrapping a standalone ApplicationContext, just
      hosted in J2EE environment, being able to access the J2EE servers
      facilities. RAR deployment is a more natural alternative to scenario of
      deploying a headless WAR file, in effect, a WAR file without any HTTP
      entry points that is used only for bootstrapping a Spring
      ApplicationContext in a J2EE environment.</p><p>RAR deployment is ideal for application contexts that do not need HTTP
      entry points but rather consist only of message endpoints and scheduled
      jobs. Beans in such a context can use application server resources such as
      the JTA transaction manager and JNDI-bound JDBC DataSources and JMS
      ConnectionFactory instances, and may also register with the platform's JMX
      server - all through Spring's standard transaction management and JNDI and
      JMX support facilities. Application components can also interact with the
      application server's JCA WorkManager through Spring's
      <code class="interfacename">TaskExecutor</code> abstraction.</p><p>Check out the JavaDoc of the <a class="ulink" href="http://static.springframework.org/spring/docs/3.0.x/javadoc-api/org/springframework/jca/context/SpringContextResourceAdapter.html" target="_top">SpringContextResourceAdapter</a> class for the configuration details
      involved in RAR deployment.</p><p><span class="emphasis"><em>For a simple deployment of a Spring ApplicationContext as a
      J2EE RAR file:</em></span> package all application classes into a RAR file,
      which is a standard JAR file with a different file extension. Add all
      required library JARs into the root of the RAR archive. Add a
      "META-INF/ra.xml" deployment descriptor (as shown in
      <code class="classname">SpringContextResourceAdapter</code>s JavaDoc) and the
      corresponding Spring XML bean definition file(s) (typically
      "META-INF/applicationContext.xml"), and drop the resulting RAR file into
      your application server's deployment directory.</p><div class="note" style="margin-left: 0.5in; margin-right: 0.5in;"><table border="0" summary="Note"><tr><td rowspan="2" align="center" valign="top" width="25"><img alt="[Note]" src="images/note.gif"></td><th align="left">Note</th></tr><tr><td align="left" valign="top"><p>Such RAR deployment units are usually self-contained; they do not
        expose components to the outside world, not even to other modules of the
        same application. Interaction with a RAR-based ApplicationContext
        usually occurs through JMS destinations that it shares with other
        modules. A RAR-based ApplicationContext may also, for example, schedule
        some jobs, reacting to new files in the file system (or the like). If it
        needs to allow synchronous access from the outside, it could for example
        export RMI endpoints, which of course may be used by other application
        modules on the same machine.</p></td></tr></table></div></div></div><div class="section" lang="en"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="beans-beanfactory"></a>4.15&nbsp;The BeanFactory</h2></div></div></div><p>The <code class="classname">BeanFactory</code> provides the underlying basis
      for Spring's IoC functionality but it is only used directly in integration
      with other third-party frameworks and is now largely historical in nature
      for most users of Spring. The <code class="classname">BeanFactory</code> and
      related interfaces, such as <code class="classname">BeanFactoryAware</code>,
      <code class="classname">InitializingBean</code>,
      <code class="classname">DisposableBean</code>, are still present in Spring for the
      purposes of backward compatibility with the large number of third-party
      frameworks that integrate with Spring. Often third-party components that
      can not use more modern equivalents such as <code class="code">@PostConstruct</code> or
      <code class="code">@PreDestroy</code> in order to remain compatible with JDK 1.4 or to
      avoid a dependency on JSR-250.</p><p>This section provides additional background into the differences
      between the <code class="interfacename">BeanFactory</code> and
      <code class="interfacename">ApplicationContext</code> and how one might access
      the IoC container directly through a classic singleton lookup.</p><div class="section" lang="en"><div class="titlepage"><div><div><h3 class="title"><a name="context-introduction-ctx-vs-beanfactory"></a>4.15.1&nbsp;<code class="interfacename">BeanFactory</code> or
        <code class="interfacename">ApplicationContext</code>?</h3></div></div></div><p>Use an <code class="interfacename">ApplicationContext</code> unless you
        have a good reason for not doing so.</p><p>Because the <code class="interfacename">ApplicationContext</code>
        includes all functionality of the
        <code class="interfacename">BeanFactory</code>, it is generally recommended
        over the <code class="interfacename">BeanFactory</code>, except for a few
        situations such as in an <code class="classname">Applet</code> where memory
        consumption might be critical and a few extra kilobytes might make a
        difference. However, for most typical enterprise applications and
        systems, the <code class="interfacename">ApplicationContext</code> is what
        you will want to use. Spring 2.0 and later makes
        <span class="emphasis"><em>heavy</em></span> use of the <a class="link" href="beans.html#beans-factory-extension-bpp" title="4.8.1&nbsp;Customizing beans using a BeanPostProcessor"><code class="interfacename">BeanPostProcessor</code> extension point</a>
        (to effect proxying and so on). If you use only a plain
        <code class="interfacename">BeanFactory</code>, a fair amount of support
        such as transactions and AOP will not take effect, at least not without
        some extra steps on your part. This situation could be confusing because
        nothing is actually wrong with the configuration.</p><p>The following table lists features provided by the
        <code class="interfacename">BeanFactory</code> and
        <code class="interfacename">ApplicationContext</code> interfaces and
        implementations.</p><div class="table"><a name="context-introduction-ctx-vs-beanfactory-feature-matrix"></a><p class="title"><b>Table&nbsp;4.8.&nbsp;Feature Matrix</b></p><div class="table-contents"><table summary="Feature Matrix" width="100%" style="border-collapse: collapse;border-top: 1.0pt solid ; border-bottom: 1.0pt solid ; border-left: 1.0pt solid ; border-right: 1.0pt solid ; "><colgroup><col align="left"><col><col></colgroup><thead><tr><th style="border-right: 1.0pt solid ; border-bottom: 1.0pt solid ; " align="center">Feature</th><th style="border-right: 1.0pt solid ; border-bottom: 1.0pt solid ; " align="center"><code class="interfacename">BeanFactory</code></th><th style="border-bottom: 1.0pt solid ; " align="center"><code class="interfacename">ApplicationContext</code></th></tr></thead><tbody><tr><td style="border-right: 1.0pt solid ; border-bottom: 1.0pt solid ; " align="left"><p>Bean instantiation/wiring</p></td><td style="border-right: 1.0pt solid ; border-bottom: 1.0pt solid ; " align="center"><p>Yes</p></td><td style="border-bottom: 1.0pt solid ; " align="center"><p>Yes</p></td></tr><tr><td style="border-right: 1.0pt solid ; border-bottom: 1.0pt solid ; " align="left"><p>Automatic
                <code class="interfacename">BeanPostProcessor</code>
                registration</p></td><td style="border-right: 1.0pt solid ; border-bottom: 1.0pt solid ; " align="center"><p>No</p></td><td style="border-bottom: 1.0pt solid ; " align="center"><p>Yes</p></td></tr><tr><td style="border-right: 1.0pt solid ; border-bottom: 1.0pt solid ; " align="left"><p>Automatic
                <code class="interfacename">BeanFactoryPostProcessor</code>
                registration</p></td><td style="border-right: 1.0pt solid ; border-bottom: 1.0pt solid ; " align="center"><p>No</p></td><td style="border-bottom: 1.0pt solid ; " align="center"><p>Yes</p></td></tr><tr><td style="border-right: 1.0pt solid ; border-bottom: 1.0pt solid ; " align="left"><p>Convenient
                <code class="interfacename">MessageSource</code> access (for
                i18n)</p></td><td style="border-right: 1.0pt solid ; border-bottom: 1.0pt solid ; " align="center"><p>No</p></td><td style="border-bottom: 1.0pt solid ; " align="center"><p>Yes</p></td></tr><tr><td style="border-right: 1.0pt solid ; " align="left"><p><code class="interfacename">ApplicationEvent</code>
                publication</p></td><td style="border-right: 1.0pt solid ; " align="center"><p>No</p></td><td style="" align="center"><p>Yes</p></td></tr></tbody></table></div></div><br class="table-break"><p>To explicitly register a bean post-processor with a
        <code class="interfacename">BeanFactory</code> implementation, you must
        write code like this:</p><pre class="programlisting">ConfigurableBeanFactory factory = <span class="hl-keyword">new</span> XmlBeanFactory(...);

<span class="hl-comment">// now register any needed BeanPostProcessor instances</span>
MyBeanPostProcessor postProcessor = <span class="hl-keyword">new</span> MyBeanPostProcessor();
factory.addBeanPostProcessor(postProcessor);

<span class="hl-comment">// now start using the factory</span></pre><p>To explicitly register a
        <code class="classname">BeanFactoryPostProcessor</code> when using a
        <code class="interfacename">BeanFactory</code> implementation, you must
        write code like this:</p><pre class="programlisting">XmlBeanFactory factory = <span class="hl-keyword">new</span> XmlBeanFactory(<span class="hl-keyword">new</span> FileSystemResource(<span class="hl-string">"beans.xml"</span>));

<span class="hl-comment">// bring in some property values from a Properties file</span>
PropertyPlaceholderConfigurer cfg = <span class="hl-keyword">new</span> PropertyPlaceholderConfigurer();
cfg.setLocation(<span class="hl-keyword">new</span> FileSystemResource(<span class="hl-string">"jdbc.properties"</span>));

<span class="hl-comment">// now actually do the replacement</span>
cfg.postProcessBeanFactory(factory);</pre><p>In both cases, the explicit registration step is inconvenient, which
        is one reason why the various
        <code class="interfacename">ApplicationContext</code> implementations are
        preferred above plain <code class="interfacename">BeanFactory</code>
        implementations in the vast majority of Spring-backed applications,
        especially when using <code class="literal">BeanFactoryPostProcessors</code> and
        <code class="classname">BeanPostProcessors</code>. These mechanisms implement
        important functionality such as property placeholder replacement and
        AOP.</p></div><div class="section" lang="en"><div class="titlepage"><div><div><h3 class="title"><a name="beans-servicelocator"></a>4.15.2&nbsp;Glue code and the evil singleton</h3></div></div></div><p>It is best to write most application code in a dependency-injection
        (DI) style, where that code is served out of a Spring IoC container, has
        its own dependencies supplied by the container when it is created, and
        is completely unaware of the container. However, for the small glue
        layers of code that are sometimes needed to tie other code together, you
        sometimes need a singleton (or quasi-singleton) style access to a Spring
        IoC container. For example, third-party code may try to construct new
        objects directly (<code class="literal">Class.forName()</code> style), without the
        ability to get these objects out of a Spring IoC container.
        If
        the object constructed by the third-party code is a small stub or proxy,
        which then uses a singleton style access to a Spring IoC container to
        get a real object to delegate to, then inversion of control has still
        been achieved for the majority of the code (the object coming out of the
        container). Thus most code is still unaware of the container or how it
        is accessed, and remains decoupled from other code, with all ensuing
        benefits. EJBs may also use this stub/proxy approach to delegate to a
        plain Java implementation object, retrieved from a Spring IoC container.
        While the Spring IoC container itself ideally does not have to be a
        singleton, it may be unrealistic in terms of memory usage or
        initialization times (when using beans in the Spring IoC container such
        as a Hibernate <code class="interfacename">SessionFactory</code>) for each
        bean to use its own, non-singleton Spring IoC container.</p><p>Looking up the application context in a service locator style is
        sometimes the only option for accessing shared Spring-managed
        components, such as in an EJB 2.1 environment, or when you want to share
        a single ApplicationContext as a parent to WebApplicationContexts across
        WAR files. In this case you should look into using the utility class
        <a class="ulink" href="http://static.springsource.org/spring/docs/3.0.x/javadoc-api/org/springframework/context/access/ContextSingletonBeanFactoryLocator.html" target="_top"><code class="classname">ContextSingletonBeanFactoryLocator</code></a>
        locator that is described in this <a class="ulink" href="http://blog.springsource.com/2007/06/11/using-a-shared-parent-application-context-in-a-multi-war-spring-application/" target="_top">SpringSource team blog entry</a>.</p></div></div><div class="footnotes"><br><hr width="100" align="left"><div class="footnote"><p><sup>[<a name="ftn.d0e1637" href="#d0e1637" class="para">1</a>] </sup>See <a class="xref" href="overview.html#background-ioc" title="Background">Background</a></p></div><div class="footnote"><p><sup>[<a name="ftn.d0e3664" href="#d0e3664" class="para">2</a>] </sup>See <a class="xref" href="beans.html#beans-factory-collaborators" title="4.4.1&nbsp;Dependency injection">Section&nbsp;4.4.1, &#8220;Dependency injection&#8221;</a></p></div></div></div><!--Begin LoopFuse code--><script src="http://loopfuse.net/webrecorder/js/listen.js" type="text/javascript"></script><script type="text/javascript">
			_lf_cid = "LF_48be82fa";
			_lf_remora();
		</script><!--End LoopFuse code--><div class="navfooter"><hr><table width="100%" summary="Navigation footer"><tr><td width="40%" align="left"><a accesskey="p" href="spring-core.html">Prev</a>&nbsp;</td><td width="20%" align="center"><a accesskey="u" href="spring-core.html">Up</a></td><td width="40%" align="right">&nbsp;<a accesskey="n" href="resources.html">Next</a></td></tr><tr><td width="40%" align="left" valign="top">Part&nbsp;III.&nbsp;Core Technologies&nbsp;</td><td width="20%" align="center"><a accesskey="h" href="index.html">Home</a></td><td width="40%" align="right" valign="top">&nbsp;5.&nbsp;Resources</td></tr></table></div></body></html>